Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Pixelairport's avatar

DB query which has exactly two relations

I build a message system. When a user creates a new message to a user i will check if there is already a conversation for theses users to attach the message. Otherwise a new thread will be opened. I have problems to create the query in laravel.

return $this->whereHas('participants', function ($query) { $query->where('user_id','=',1)->where('user_id','=',57); })->get();

This is my first idea. I also tried whereIn, but this is checking for just one id (1 or 57). I need the conversation, where only 1 and 57 are participants. Also if there is another thread where there are 1, 57 and 173 (for example) participants. Hope you understand what i mean. And also hope you can help me with this problem. thx.

0 likes
5 replies
Sinnbeck's avatar

Here your are checking if user_id is both 1 and 57. That will never happen :)

$ids = [1, 57];
return $this->whereHas('participants', function ($query) { $query->whereIn('user_id', $ids)->get();
Pixelairport's avatar

It returns a result. But i get every conversion where user 1 or 57 is involved. I need exactly the one conversion between these two. But i had a idea. Maybe not perfect, but works for my first version. Sometimes I just have to talk (or write) about my problem to think again in another way about it... so thx ;) ... Here is what works for me now (I first get the results of all conversions with the ids and then check the count of participants with the array):

$q = $this->whereHas('participants');        
foreach($aUserIds as $k => $v) {
            $q->whereHas('participants', function ($query) use($v) {
                $query->where('user_id', $v);
            });
        }

        foreach($q->get() as $conversion){
            if($conversion->participants->count()==count($aUserIds)){
                return $conversion;
            }
        }

        return null;
Sinnbeck's avatar

If you can tell me about your setup I can perhaps give you a better solution. How is the relation between Message and Participant ?

And how does Participant table look?

Pixelairport's avatar

Participant is just a relation table which has thread_id and user_id. The users are attached with this tabel to the treads. But i think that is ok for now, because it works. Maybe i will refactor it, when i have time. thx

Please or to participate in this conversation.