在数据库级别通过急切加载的数据筛选模型


Filtering models by eager loaded data, at the database level

在laravel文档中,他们讨论了急于加载相关数据以解决N+1查询问题。我想根据这些关系中的数据过滤我的数据,而不必迭代结果(也就是说,我希望在查询时完成)

文档中使用的示例如下:

$books = App'Book::with('author.contacts')->get();

如果我想过滤这些书,只包括作者居住在邮政编码为12345的人,我该怎么做?

以下两个查询都不适用于我:

$books = App'Book::with('author.contacts')->where('zip', 12345)->get();
$books = App'Book::with('author.contacts')->where('author.contacts.zip', 12345)->get();

在Eloquent中有一个简单的方法可以做到这一点吗?

为了实现您想要的目标,您可以使用以下查询:

App'Book::with('author.contacts')
->whereHas('author.contacts' => function($q){ 
     $q->where('zip', 12345)}
)
->get();

可以说,您也可以在contacts模型中使用类似的查询,大致如下:

public function withZipCode()
{
    return Contacts::where('zip', 12345);
}

老实说,我还没有试过,但它应该有效。