首页 留言板 后台管理

搜索中...

未找到与 "" 相关的文章

换个关键词试试看

输入关键词搜索文章

支持搜索标题、内容、摘要

Eloquent ORM 高级技巧:关联、预加载与查询优化

admin · 2026-04-11 06:57 · Laravel · 3

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

评论 (0)

暂无评论,来说两句吧!

发表评论