我在Eloquent中有以下模型:组,线程,注释和用户。我想找到特定用户在特定组中的所有评论。
这是我目前的方法:
$group->threads->each(function ($thread) use ($user_id)
{
$user_comments = $thread->comments->filter(function ($comment) use ($user_id)
{
return $comment->owner_id == $id;
});
});
这看起来像地狱一样丑陋,可能像地狱一样慢,我只是想摆脱它。在Eloquent中最快和最优雅的方法是什么才能得到我的结果集?
patricus解决方案为我指明了正确的方向。我交叉将我的问题发布到laracasts论坛,并得到Jarek Tkaczyk的大力帮助,他也经常访问该网站。
hasManyThrough()
因为Group
模型是要走的路:
public function comments()
{
return $this->hasManyThrough('ThreadComment', 'Thread');
}
但是,有几点警告:
$group->comments()
,NOT $group->comments
)get()
改为a delete()
,因为您将获得column的歧义错误updated_at
。您也不能加上前缀,这只是Eloquent的工作方式。如果要删除特定组中特定用户的所有评论,则必须做一些不同的操作:
$commentsToDelete = $group->comments()
->where('threads_comments.owner_id', $id)
->select('threads_comments.id')
->lists('id');
ThreadComment::whereIn('id', $commentsToDelete)->delete();
您基本上会在第一个查询中获取所有相关的ID,然后在第二个查询中批量删除它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句