在 Laravel 框架里,模型(Model)是 Eloquent ORM 的核心,它把数据库表映射成 PHP 对象,让你用面向对象的方式操作数据。本文从实际开发角度,梳理 Laravel 模型的使用方法与常见技巧。
一、创建与配置模型
使用 Artisan 命令可以快速生成模型:
php artisan make:model Post -m
加上 -m 会同时生成迁移文件。默认模型对应复数形式的表名,例如 Post 对应 posts。如果表名不符合约定,可以手动指定:
class Post extends Model
{
protected $table = 'articles';
protected $primaryKey = 'post_id';
public $timestamps = false;
}
二、基础查询与增删改
Eloquent 提供了链式调用,查询非常直观:
// 查询全部
$posts = Post::all();
// 条件查询
$post = Post::where('status', 1)->orderBy('created_at', 'desc')->get();
// 创建记录
$post = new Post();
$post->title = 'Laravel 模型';
$post->content = '内容';
$post->save();
// 批量赋值
Post::create([
'title' => '新文章',
'content' => '正文',
]);
// 更新
$post->update(['title' => '新标题']);
// 删除
$post->delete();
注意:使用create()批量赋值前,必须在模型中定义$fillable或$guarded,否则会抛出 MassAssignmentException。
三、模型关联
关联是模型最强大的功能之一,常见有一对一、一对多、多对多。
1. 一对多
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
使用关联:
$user = User::find(1);
foreach ($user->posts as $post) {
echo $post->title;
}
$post = Post::find(1);
echo $post->user->name;
2. 多对多
class Post extends Model
{
public function tags()
{
return $this->belongsToMany(Tag::class);
}
}
多对多需要一张中间表,例如 post_tag,并包含 post_id 与 tag_id。
四、查询作用域与访问器
把常用查询条件封装成局部作用域,代码更整洁:
public function scopePublished($query)
{
return $query->where('status', 1);
}
// 调用
Post::published()->get();
访问器可以格式化字段输出:
public function getTitleAttribute($value)
{
return ucfirst($value);
}
Laravel 8 之后推荐使用 Attribute 类定义访问器,写法更现代:
protected function title(): Attribute
{
return Attribute::make(
get: fn ($value) => ucfirst($value),
);
}
五、软删除与预加载
软删除只需在模型中使用 SoftDeletes trait,并在迁移中添加 deleted_at 字段:
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
}
预加载可以避免 N+1 查询问题:
$posts = Post::with('user', 'tags')->get();
六、实用建议
- 合理使用
$fillable,避免批量赋值漏洞。 - 关联查询优先使用
with()预加载。 - 复杂查询可拆分为作用域,提升可读性。
- 模型事件(creating、updating 等)适合处理日志、缓存清理。
掌握 Laravel 模型的核心用法后,你会发现数据库操作变得非常优雅。建议多阅读官方文档,并在项目中不断实践关联与作用域,逐步形成自己的最佳实践。
评论 (0)
还没有评论,快来抢沙发吧~