0

I need to check if ManyToMany relationship exists. I have a business that can have many members and members that can have many businesses.

I have pivot table: business_member. I am trying to use the code I found in this post, but I'm getting an error on Laravel.

When I try to run the mysql query from an editor, I get no errors and an empty results.

In my Business model:

public function membersCount()
{
   return $this->belongsToMany('App\Member')->selectRaw('count(members.member_id) as aggregate')->groupBy('pivot_business_id');
}

public function getMembersCount()
{
   if ( ! array_key_exists('membersCount', $this->relations)) $this->load('membersCount');

   $related = $this->getRelation('membersCount')->first();

   return ($related) ? $related->aggregate : 0;
}

In my controller:

$business = Business::findOrFail($id);

dd($business->getMembersCount());

I get this error:

SQLSTATE[42000]: 
Syntax error or access violation: 
1055 'ccf.business_member.member_id' isn't in GROUP BY 
(SQL: select count(members.member_id) as aggregate, `business_member`.`business_id` as `pivot_business_id`, `business_member`.`member_id` as `pivot_member_id` from `members` inner join `business_member` on `members`.`member_id` = `business_member`.`member_id` where `business_member`.`business_id` in (2) group by `pivot_business_id`)
Braiam
  • 1
  • 11
  • 47
  • 78
Sigal Zahavi
  • 1,045
  • 2
  • 21
  • 42

1 Answers1

1

It is much easier than that. First you need to define manyToMany relationship in your Business model like this:

/**
 * The members that belong to the business.
 */
public function members()
{
    return $this->belongsToMany('App\Members');
}

If you want to check how many members a given business has you can do it like this for example:

$business = Business::findOrFail($id);
dd($business->members()->count());
pnsh
  • 164
  • 1
  • 3