Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous

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))

like image 926
Lizesh Shakya Avatar asked Dec 08 '22 12:12

Lizesh Shakya


2 Answers

In last where clause, there is "id=1". You need to express it as "table_name.id=1".

like image 83
Ravindu_Dilshan Avatar answered Apr 19 '23 23:04

Ravindu_Dilshan


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

like image 23
ManojKiran Appathurai Avatar answered Apr 19 '23 23:04

ManojKiran Appathurai