简体   繁体   中英

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

As we know, this is a bad option for mysql

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

If we have 3 authors with 3 posts each, eloquent make 4 SQL queries (1 for authors, and 1 more per author for get their posts)

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

This is better for mysql, because now we have only 2 SQL queires (1 for authors and 1 for posts).

Queries are like:

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

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

But, is it possible maintain the last PHP code but making a SQL query like this?

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

You can try local scopes. The code won't get exactly like that, but may end like:

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

And you would define the scope like this:

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

Official documentatation: https://laravel.com/docs/5.5/eloquent#local-scopes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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