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

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?

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.