Laravel渴望加载内部约束不受限制,如果后面嵌套'与'
问题描述:
这是一个问题和我自己的答案(我偶然发现的解决方案)。 Laravel的文档没有提到这一点,它给我带来了几个小时的编程痛苦。Laravel渴望加载内部约束不受限制,如果后面嵌套'与'
比方说,我们有评论和投票(评论)的职位。 Laravel最喜欢的例子。模型和关系是教科书(来自Laravel的文档)。帖子有评论,评论有投票。
所以,
$comments_ids = [1,6,7,22];
Post::where('id', $post_id)
->with(['comments' => function($query) use ($comments_ids) {
$query->whereIn('id', $comments_ids);
}])
->with('comments.votes')
->first();
所以,我应该期待用后其意见,IDS是1,6,7,22和选票渴望加载。
但不是那么快!我收到所有评论!他们全部! ...为什么?
答
下面是这个问题的答案:
因为,我们渴望负载意见,然后我们加载票,得票强制所有评论加载。
此:
$comments_ids = [1,6,7,22];
Post::where('id', $post_id)
->with(['comments' => function($query) use ($comments_ids) {
$query->whereIn('id', $comments_ids);
}])
->with('comments.votes') //this forces Builder to completely ignore whereIn clause above.
->first();
应该写成如下:
$comments_ids = [1,6,7,22];
Post::where('id', $post_id)
->with(['comments' => function($query) use ($comments_ids) {
$query->whereIn('id', $comments_ids)
->with('votes'); //eager load votes with filtered comments
}])
->first();
然后你会得到在$ comments_ids变量指定ID的注释。并投票热切与他们。
这个小小的细微差别引起了很多头痛。