Search code examples
mysqllaraveleloquenteloquent-relationship

Check if 2 records of different with different user_id exist in child table in Laravel


I am making a chat system in laravel. My table structure is

thread (id, subject) participants (id, thread_id, user_id) messages (id, thread_id, body, file)

I have built relationships " thread hasMany participants", "thread hasMany messages"

Now the scenario is: Let's suppose there are two users with IDs 3 and 4. I want to check if there is any thread that exists having both participants matching these two user IDs.

In the other words, I can say "If user 3 and user 4 are participants of any thread"

How do I make this query?


Solution

  • When you want to determinate if exists any thread which has both of users you can use whereHas method which allow to querying relationship. e.g

    $userIds = [ 3, 4 ];
    $exists = Thread::whereHas( 'participants', function ( $query ) use ( $userIds ) {
        $query->whereIn( 'user_id', $userIds )
    }, '>=', count( $userIds ) )->exists();