簡體   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