Eloquent 是 Laravel 的 ORM 实现,提供了极其优雅的数据库操作方式。
定义关联
一对一
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
一对多
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
多对多
class Post extends Model
{
public function tags()
{
return $this->belongsToMany(Tag::class);
}
}
预加载解决 N+1 问题
// 糟糕:会产生 N+1 查询
$posts = Post::all();
foreach ($posts as $post) {
echo $post->author->name;
}
// 正确:使用 with 预加载
$posts = Post::with('author')->get();
foreach ($posts as $post) {
echo $post->author->name;
}
查询作用域
class Post extends Model
{
public function scopePublished($query)
{
return $query->where('status', 'published');
}
public function scopePopular($query)
{
return $query->where('views', '>', 1000);
}
}
// 使用
$posts = Post::published()->popular()->get();
批量赋值与填充
$post = Post::create([
'title' => 'Hello',
'content' => 'World',
]);
记得在模型中定义 $fillable 或 $guarded。