Parth Chavda Parth Chavda - 4 months ago 24
PHP Question

code optimization laravel.i want to retrived a avilable group where member not already exist

there are three tables

user,memember,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


now i want those groups where the member is not assigned.
i have done 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);

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.