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

标签 php mysql eloquent

正如我们所知,这对 mysql 来说是一个糟糕的选择

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

如果我们有 3 位作者,每人有 3 篇文章,Eloquent 会进行 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

关于php - Laravel/ Eloquent : replace with() for leftjoin() or join(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46286842/

相关文章:

laravel Eloquent ORM - 如何获取已编译的查询?

php - Symfony 缺少 bootstrap.php.cache

php - 我需要一个 RegExp 来只匹配拉丁字符而不匹配其他字符

MySQL - 使用 GROUP BY 和 DESC

mysql - docker phpmyadmin 无法访问本地主机

php - laravel mongodb 嵌套集合关系

php - 我怎样才能加入 Eloquent : Relationships?

php - 十进制数的二进制等效值中两个 1 之间的最大间隔

php - Laravel 应用程序的结构(API、后台、前台)

C#,DataGridView - 选择新行后包含垃圾