如果后跟嵌套'with',则 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 的注释。选票渴望装满他们。

这个小小的细微差别引起了很多头痛。

最新更新