dougui5419 2016-09-29 10:07
浏览 34
已采纳

代码优化 - 我想检索一个尚不存在成员的可用组

There are three tables:

user,member,group_member(relation mem_id,group_id) many to many

I have defined a relation for a group on member model

public function group(){
        return $this->belongsToMany('Model\Group', 'group_member', 'mem_id', 'group_id');
    }

using the above relation I can retrieve a member assigned to a group using

   Model\Member::with('group')->find('member_id')

now I want those groups where the member is not assigned.

I am able to do this using

$arg['ids'] = $member->group->lists('_id');
        $group = Group::where('user_id',$user_id)->whereNotIn('_id',$arg['ids'])->limit($arg['limit'])->offset($arg['offset'])->get();

Is there another option rather than using a subquery?

  • 写回答

1条回答 默认 最新

  • duanmian1085 2016-09-29 12:13
    关注

    You can only retrieve groups related to Member object with its relations. In order to get all unrelated groups, you'll need to run a query on Group model.

    The following code should do the trick:

    $unrelatedGroups = Group::whereDoesnHave('member', function($query) use ($user_id) {
      $query->where('id', $user_id);
    })->get();
    

    This will return all groups that don't have a member with given $user_id. Just make sure you have a many-to-many relation defined in your Group model called member that links to all members of given group.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看