php .\artisan make:model Home/Member
$table
属性,值是不要前缀的表名。(如果不指定则使用类名的复数形式)$primaryKey
属性,如果需要使用AR模式的find(Model::find(n)
)方法,且主键字段不是id则需要指定主键。$timestamps
属性,值设置为false。如果不设置,默认会操作表中的created_at和updated_at字段。$fillable
属性,表示使用模型插入数据时,允许插入到数据库的字段信息。定义$guarded
设置排除入库字段。class Member extends Model
{
protected $table = 'member';
protected $primaryKey = "id";
public $timestamps = false;
protected $fillable = ["id", "name", "age", "email"];
}
use App\Home\Member;
Member::get()
$model = new Member();
$model->get();
save()
即可。$member = new Member();
$member->name = "Lisa";
$member->age = 15;
$result = $member->save();
dd($result); // boolean
public function test8(Request $request) {
...
}
# 获取所有参数
$request->all();
# 获取某个参数
$request->get('name');
# 只获取某些参数
$request->only(['name', 'age']);
# 不获取某些参数
$request->except(['name', 'age']);
public function test8(Request $request) {
$member = new Member();
$result = $member->create($request->all());
}
$data = Member::find(5);
结果集默认是一个对象。如果要将结果集转换为数组,则需要在最终添加框架自己封装的方法toArray()
public function test9() {
$data = Member::find(5)->toArray();
dd($data);
}
$data = Member::where("id", ">", 5)->first();
$data = Member::where("id", ">", 5)->select(["name", "age"])->get()->toArray();
find()
返回一个模型对象,然后再为对象更新数据。public function test10() {
$data = Member::find(7);
$data->email = "[email protected]";
$data->save();
}
Member::where("id", "8")->update([
"age" => 80
]);
$data = Member::find(10);
$data->delete();
validate
方法用于验证接收的数据。如果验证通过,代码继续执行。验证失败,则抛出异常。在传统的HTTP请求中,验证失败会生成一个重定向响应。|
隔开$this->validate($request, [
"name" => "required|unique:member|max:16",
"age" => "required|integer|min:1|max:120",
"email" => "required|email"
]);
$errors
变量。foreach ($errors->all() as $error){
echo $error;
}
composer require caouecs/laravel-lang