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.
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;
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