douwu5428 2015-02-10 16:01
浏览 68
已采纳

在Laravel Eloquent中获取和过滤关系

I have the following models in Eloquent: groups, threads, comments and users. I want to find all comments in a specific group from a specific user.

This is my current approach:

$group->threads->each(function ($thread) use ($user_id)
{
  $user_comments = $thread->comments->filter(function ($comment) use ($user_id)
  {
    return $comment->owner_id == $id;
  });
});

This looks ugly as hell, is probably slow as hell, and I just want to get rid of it. What is the fastest and most elegant way in Eloquent to get to my result set?

  • 写回答

2条回答 默认 最新

  • dongxi1320 2015-02-11 15:01
    关注

    patricus solution pointed me in the right direction. I cross posted my question to the laracasts Forum and got a lot of help from Jarek Tkaczyk who also frequently visits this site.

    hasManyThrough() for the Group model is the way to go:

    public function comments()
    {
      return $this->hasManyThrough('ThreadComment', 'Thread');
    }
    

    There a couple of caveats, though:

    1. Use the relation object instead of a collection ($group->comments(), NOT $group->comments)
    2. If you use Laravel’s soft deletes you can’t just change the get() to a delete(), because you’ll get an ambiguity error for the column updated_at. You can’t prefix it either, it’s just how Eloquent works.

    If you want to delete all comments from a specific user in a specific group you’ll have to do it a little bit differently:

    $commentsToDelete = $group->comments()
            ->where('threads_comments.owner_id', $id)
            ->select('threads_comments.id')
            ->lists('id');
    
    ThreadComment::whereIn('id', $commentsToDelete)->delete();
    

    You basically fetch all relevant IDs in the first query and then batch delete them in a second one.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀