【问题标题】:Load relations for a query result separately单独加载查询结果的关系
【发布时间】:2017-05-08 14:08:36
【问题描述】:

假设我们有两个模型 BookAuthor。 Book 模型定义了获取作者的关系:

public function author()
{
    return $this->belongsTo(Author::class, 'author_id','id');
}

如果我们想要获取 2000 年出版的所有书籍及其作者,我们可以这样做:

$books = Book::with('author')->where('publication_year', 2000)->get();

现在,如果我们想要返回 2000 年分别出版的唯一作者,该怎么办?假设 Bob 出版了三本书,Sally 出版了两本书。我们将有一个包含 5 本书但没有作者的集合,另一个包含 Bob 和 Sally 各一次的集合。

这是我得到的最接近的(这是一个简化的示例,可能包含拼写错误):

$books = Book::with('author')->where('publication_year', 2000)->get();
$authors = $books->pluck('author')->unique('id');
//this part is bad:
foreach ($books as $book) {
    unset($book['author']);
}

有没有更有效的方法来做到这一点,还是我必须设置手动 JOIN?

【问题讨论】:

    标签: laravel laravel-5


    【解决方案1】:

    如果要获取2000年出书的作者ID,可以使用whereHas()

    Author::whereHas('books', function($q) {
            $q->where('publication_year', 2000);
        })->pluck('id');
    

    【讨论】:

      【解决方案2】:

      您可以将whereIn 用作:

      $books = Book::where('publication_year', 2000)->get();
      
      $authors_id = $books->unique('author_id')->pluck('author_id');
      
      $authors = Author::whereIn('id', $authors_id)->get();
      

      【讨论】:

      • 啊,这与我之前的想法不同。我喜欢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多