Eloquent 指南 http://laravel.com/docs/4.2/eloquent包含以下内容:-
Eager Load Constraints
Sometimes you may wish to eager load a relationship, but also specify a condition for the eager load. Here's an example:
$users = User::with(array('posts' => function($query)
{
$query->where('title', 'like', '%first%');
}))->get();
In this example, we're eager loading the user's posts, but only if the post's title column contains the word "first".
如何扭转这一局面,以便只获得标题列包含“first”一词的帖子的用户?
换句话说,我只想要帖子包含“first”一词的用户,并且我想立即加载这些帖子。如果有 10 个用户,其中 3 个用户的帖子包含“first”一词,那么我的 get() 将仅返回 3 个用户,每个用户都有急切加载的帖子,且标题包含“first”。
最佳答案
我相信您正在寻找这样的东西(未经测试):
$first = 'first';
$users = User::whereHas('posts' => function($q) use ($first)
{
$q->where('title', 'like', "%{$first}%");
})->with(['posts' => function($q) use ($first)
{
$q->where('title', 'like', "%{$first}%");
}])->get();
关于php - Eloquent 渴望加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31161820/