Eloquent Model 支持无 SQL 的 CRUD:create() 需 $fillable 白名单,find()/findOrFail() 按主键查,where()->get() 返回集合,save()/update() 区分是否触发事件,delete() 默认软删除。
Laravel 的 Eloquent ORM 是默认的数据库操作方式,所有增删改查都通过模型类完成,不需要拼接 SQL 字符串或调用 DB::table()(除非特殊场景)。模型自动绑定数据表、主键、时间戳字段,省去大量样板代码。
假设你已运行 php artisan make:model Post 生成模型,并且数据库表 posts 存在,主键为 id,含 created_at 和 updated_at 字段:
class Post extends Model
{
// 默认已启用时间戳,无需额外配置
// 表名自动推导为 'posts'(类名复数)
}
create() 要求模型中定义 $fillable 白名单,否则抛出 MassAssignmentException;new + save() 则绕过批量赋值检查,适合字段来源可控时使用。
Post::create(['title' => 'Hello', 'content' => 'World']) —— 必须有 protected $fillable = ['title', 'content'];
$post = new Post(); $post->title = 'Hello'; $post->content = 'World'; $post->save(); —— 不依赖 $fillablePost::unguard(); Post::create([...]); Post::reguard();,但不推荐用于生产别无脑用 all() 查全表——它会加载全部记录到内存,数据量大时直接拖垮应用。按需选择方法:
Post::find(1) —— 按主键查,查不到返回 null
Post::findOrFail(1) —— 查不到抛出 ModelNotFoundException,常用于路由模型绑定Post::where('status', 'published')->first() —— 条件查询首条,查不到返回 null
Post::where('status', 'published')->firstOrFail() —— 条件查不到也抛异常Post::where('status', 'published')->get() —— 返回集合(Collection),不是数组,支持链式操作如 ->map()、->pluck('title')
更新分两种路径:先查后改(用模型实例),或直接条件更新(跳过模型事件和访问器)。
$post = Post::find(1); $post->title = 'New Title'; $post->save(); —— 触发 saving / saved 事件,走访问器(accessor/mutator)Post::where('id', 1)->update(['title' => 'New Title']); —— 不触发模型事件,不调用 mutator,性能略高,适合后台批量更新$post->delete() —— 软删除需先 use SoftDeletes trait,否则是物理删除Post::destroy([1, 2, 3]) —— 传 ID 数组批量删除,同样受软删除影响Post::withTrashed()->find(1)->forceDelete()
软删除字段 deleted_at 必须存在且为 nullable datetime 类型,否则 restore() 会失败。