繁体   English   中英

Laravel / Eloquent:用()替换leftjoin()或join()

[英]Laravel/Eloquent: replace with() for leftjoin() or join()

众所周知,这对于mysql来说是一个不好的选择

$authors = Authors::all();
foreach ($authors as $author) {
    echo $author->name;
    foreach ($author->posts as $post) {
        echo $post->title;
    }
}

如果我们有3位作者,每位作者3条帖子,那么雄辩地进行4条SQL查询(1位作者,每位作者1位)

$authors = Authors::with('posts')
        ->all();
foreach ($authors as $author) {
    echo $author->name;
    foreach ($author->posts as $post) {
        echo $post->title;
    }
}

这对于mysql更好,因为现在我们只有2个SQL查询器(1个用于作者,1个用于帖子)。

查询就像:

select * from `authors` where `authors`.`deleted_at` is null

select * from `posts`
    where `posts`.`deleted_at` is null and `author`.`id` in (?, ?, ?)

但是,是否可以维护最后的PHP代码,但进行这样的SQL查询呢?

select authors.*, posts.* from `authors`
    left join posts on posts.author_id = authors.id
    where `authors`.`deleted_at` is null

您可以尝试本地范围。 代码不会完全像那样,但是可能会像这样结束:

$authors = Authors::theNameYouChooseForTheScope()->get();

您将定义如下范围:

public function scopeTheNameYouChooseForTheScope($query)
{
    return $query->leftJoin('posts', 'authors.id', '=', 'posts.author_id')
}

官方文档: https : //laravel.com/docs/5.5/eloquent#local-scopes

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM