Eloquent Model 支持无 SQL 的 CRUD:create() 需 $fillable 白名单,find()/findOrFail() 按主键查,where()->get() 返回集合,save()/update() 区分是否触发事件,delete() 默认软删除。

直接用 Eloquent Model 做 CRUD,不用手写 SQL
Laravel 的 Eloquent ORM 是默认的数据库操作方式,所有增删改查都通过模型类完成,不需要拼接 SQL 字符串或调用 DB::table()(除非特殊场景)。模型自动绑定数据表、主键、时间戳字段,省去大量样板代码。
假设你已运行 php artisan make:model Post 生成模型,并且数据库表 posts 存在,主键为 id,含 created_at 和 updated_at 字段:
class Post extends Model
{
// 默认已启用时间戳,无需额外配置
// 表名自动推导为 'posts'(类名复数)
}
创建记录:用 create() 或 new + save()
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();—— 不依赖 $fillable - 如果想临时允许所有字段批量赋值,可用
Post::unguard(); Post::create([...]); Post::reguard();,但不推荐用于生产
查询记录:all()、find()、where() 和 firstOrFail() 的区别
别无脑用 all() 查全表——它会加载全部记录到内存,数据量大时直接拖垮应用。按需选择方法:
立即学习“PHP免费学习笔记(深入)”;
-
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')
更新和删除:save()、update()、delete() 都是实例方法或静态方法
更新分两种路径:先查后改(用模型实例),或直接条件更新(跳过模型事件和访问器)。
-
$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()—— 软删除需先 useSoftDeletestrait,否则是物理删除 -
Post::destroy([1, 2, 3])—— 传 ID 数组批量删除,同样受软删除影响 - 硬删(绕过软删除):用
Post::withTrashed()->find(1)->forceDelete()
软删除字段 deleted_at 必须存在且为 nullable datetime 类型,否则 restore() 会失败。











