跳转到主要内容
约 2 分钟阅读

模型关联 (Relationships)

现实世界中的数据表往往相互关联。Eloquent 提供了简单而强大的机制来定义这些关系,使关联查询如同调用普通属性一样自然。

常见关联类型定义

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class User extends Model
{
    // 一对多:一个用户有多篇文章
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }
}

class Post extends Model
{
    // 反向关联:文章属于某个用户
    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    // 多对多:文章包含多个标签
    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }
}

预加载 (Eager Loading) 消除 N+1 查询问题

// ❌ 低效方式:产生 1 + N 次 SQL 查询
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->author->name;
}

// ✅ 渴求式预加载:仅产生 2 次高效查询!
$posts = Post::with(['author', 'tags'])->get();