必须正确使用Eloquent ORM的模型定义、查询链式调用、批量赋值控制与关系声明机制;需生成规范模型、设置$fillable或$guarded、显式声明表名与时间戳、安全增删改查、预加载避免N+1、定义作用域、类型转换及访问器/修改器。

要在 Laravel 项目中用面向对象的方式操作数据库,避免手写 SQL、防止字段注入、自动处理时间戳和关联加载,就必须正确使用 Eloquent ORM 的模型定义、查询链式调用、批量赋值控制与关系声明机制。
创建并配置基础模型
第一步是生成符合命名规范的模型文件,它将作为数据库表的 PHP 映射入口。
运行命令:php artisan make:model User -mcr,这会同时创建模型、迁移文件、控制器和资源类。
打开 app/Models/User.php,确认类已继承 Illuminate\Database\Eloquent\Model。
【必须设置 $fillable 或 $guarded】,否则调用 create() 时会抛出 MassAssignmentException 异常——这是 Laravel 的安全强制机制,不是可选配置。
在模型中显式声明允许批量赋值的字段:protected $fillable = ['name', 'email', 'password'];
如果表名不是 users(比如叫 member_list),必须加上:protected $table = 'member_list';
若数据库表不含 created_at 和 updated_at 字段,务必关闭时间戳:public $timestamps = false;
执行安全的增删改查操作
查询全部用户:User::all(),返回 Collection 对象,不是数组。
按主键精确查找:User::find(5),查不到返回 null;User::findOrFail(5) 查不到直接抛 404 异常,适合 Web 路由场景。
条件查询第一条:User::where('email', 'test@example.com')->first(),注意 first() 返回单个模型实例,get() 才返回集合。
插入新记录有两种方式:
方法一(推荐):使用 create(),前提是字段已在 $fillable 中声明:User::create(['name' => 'Leo', 'email' => 'leo@test.com', 'password' => bcrypt('123')]);
方法二:实例化后赋值再保存:$user = new User; $user->name = 'Leo'; $user->email = 'leo@test.com'; $user->save();
更新操作优先用实例方式:$user = User::find(1); $user->name = 'Leo Chen'; $user->save();
这样会触发 saving、updated 等模型事件;而静态 update() 不触发事件:User::where('id', 1)->update(['name' => 'Leo Chen']);
删除单条记录:$user = User::find(1); $user->delete();
批量删除:User::where('status', 0)->delete();
硬删除(绕过软删除):User::withTrashed()->where('id', 1)->forceDelete();
定义并加载模型关联关系
一对一关系:比如 User 拥有一个 Profile。
在 User 模型中添加方法:public function profile() { return $this->hasOne(Profile::class); }
调用时直接访问属性:$user->profile —— 这会触发一次额外查询(N+1 问题初现);
要避免 N+1,必须预加载:User::with('profile')->get();
此时 Eloquent 会先查 users,再用 IN 查询所有关联 profile,只发两条 SQL。
一对多关系:比如 User 有多个 Post。
在 User 模型中写:public function posts() { return $this->hasMany(Post::class); }
获取时用:$user->posts 或预加载:User::with('posts')->get();
反向关联(Post 所属 User)在 Post 模型中定义:public function user() { return $this->belongsTo(User::class); }
注意:belongsTo 默认查找外键 user_id,若字段名不同(如 author_id),需显式传参:return $this->belongsTo(User::class, 'author_id');
构建可复用的查询作用域
本地作用域用于封装常用 WHERE 条件,命名必须以 scope 开头,参数固定为 $query。
在 User 模型中添加:public function scopeActive($query) { return $query->where('status', 1); }
调用时去掉 scope 前缀,首字母小写:User::active()->get();
支持链式叠加:User::active()->orderBy('name')->get();
全局作用域影响所有该模型的查询,适合软删除、租户隔离等场景。
新建类 app/Scopes/ActiveScope.php:class ActiveScope implements Scope { public function apply(Builder $builder, Model $model) { $builder->where('status', 1); } }
在模型的 booted() 方法中注册:protected static function booted() { static::addGlobalScope(new ActiveScope); }
临时禁用全局作用域:User::withoutGlobalScopes()->get();
【不可逆操作】 全局作用域一旦注册,所有查询默认生效,包括 count()、exists() 等,务必测试覆盖。
处理字段类型转换与虚拟属性
用 $casts 自动转换字段类型,避免手动 (int) 或 json_decode。
例如将 JSON 字段转为数组:protected $casts = ['meta' => 'array', 'is_published' => 'boolean'];
日期字段可转为 Carbon 实例:'published_at' => 'datetime:Y-m-d H:i'
敏感字段不随 toArray() 或 API 响应输出:protected $hidden = ['password', 'remember_token'];
访问器(Accessor)用于读取时格式化属性:
在模型中添加方法:public function getFullNameAttribute() { return $this->first_name . ' ' . $this->last_name; }
调用时直接用 $user->full_name,无需括号。
修改器(Mutator)用于写入前处理:public function setEmailAttribute($value) { $this->attributes['email'] = strtolower($value); }
这样每次赋值 $user->email = 'TEST@EXAMPLE.COM',存入数据库的都是小写。
序列化时追加虚拟字段:protected $appends = ['avatar_url'];
再定义对应访问器:public function getAvatarUrlAttribute() { return 'https://cdn.example.com/avatars/' . $this->id . '.jpg'; }
只要调用 $user->toArray() 或返回 JSON 响应,avatar_url 就会自动包含在结果里。


















