I am building a website where many members can join many groups.
//User.php
public function groups()
{
return $this->belongsToMany(Group::class, 'group_member', 'member_id', 'group_id');
}
The function to retrieve related members from the group id
//UserRepository.php
public function getRelatedMembersByGroupIds(array $groupIds)
{
$members = User::whereHas('groups', function ($query) use ($groupIds) {
return $query->whereIn('groups.id', $groupIds);
});
return $members->get();
}
The repository is being called from the UserController
//UserController.php
public function getRelatedMembersByGroupIds(Request $request)
{
$groupIds = $request->get('group_ids');
$members = $this->userRepository->getRelatedMembersByGroupIds($groupIds);
$responses = [
'status' => 'success',
'groupRelatedMembers' => $members
];
return response()->json($responses);
}
It returns
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select users.* from users where exists (select * from groups inner join group_member on groups.id = group_member.group_id where users.id = group_member.member_id and groups.id in (1) and groups.deleted_at is null and id = 1))
In last where clause, there is "id=1". You need to express it as "table_name.id=1".
i am not daam sure but it may work
Your Code
public function getRelatedMembersByGroupIds(array $groupIds)
{
$members = User::whereHas('groups', function ($query) use ($groupIds) {
return $query->whereIn('groups.id', $groupIds);
});
return $members->get();
}
Can You dd($members)
and share the result so i will dig deep into the issue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With