简体   繁体   中英

Laravel Collection - Condition in belongsToMany relationship with whereHas equivalent

I've 3 tables:

Users:

Schema::create('users', function (Blueprint $table) {
    $table->unsignedInteger('id')->unique();
    $table->string('name', 50)->nullable();
    $table->timestamps();
});

Conversations:

Schema::create('conversations', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('token', 50)->nullable();
    $table->timestamps();
});

And User_Conversation:

Schema::create('conversation_user', function (Blueprint $table) {
    $table->unsignedInteger('conversation_id');
    $table->unsignedInteger('user_id');
    $table->dateTime('read_at')->nullable();
});

One conversation can have 2 users.

I have this class for Users:

class User extends Model {
    public function conversations(){
        return $this->belongsToMany(Conversation::class, 'conversation_user', 'user_id', 'conversation_id');
    }

    public function getConversationWith($user_id){
        return $this->conversations()->whereHas('users', function ($q) use ($user_id) {
            $q->where('ml_users.user_id', $user_id);
        })->first();
    }
}

My problem: I need to change the getConversationWith() method to:

public function getConversationWith($user_id){
    return $this->conversations->where('users.user_id', $user_id)->first();
    // Or this
    return $this->conversations->whereIn('users.user_id', [$this->id, $user_id])->first();
}

To get conversations with given user_id.

Is there a way to do this with collections ?

Thank in advance

You can accomplish that like bellow, but it will not perform well if you have a big dataset.

class User extends Model
{
    public function conversations()
    {
        return $this->belongsToMany(Conversation::class, 'conversation_user', 'user_id', 'conversation_id');
    }

    public function getConversationWith($user_id)
    {
        // conversation IDs from target user
        $conversationIds = Conversation::whereHas('user', function($query) use ($user_id)
        {
            $query->where('users.id', $user_id);
        })->pluck('id')->toArray();

        // all conversations from the current user where target user has participated
        return $this->conversations()->whereIn('conversations.id', $conversationIds)->get();
    }
}

Hope it helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM