簡體   English   中英

Laravel 集合 - 與 whereHas 等價的belongsToMany 關系中的條件

[英]Laravel Collection - Condition in belongsToMany relationship with whereHas equivalent

我有3張桌子:

用戶:

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

對話:

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

和 User_Conversation:

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

一個對話可以有 2 個用戶。

我為用戶開設了這個課程:

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();
    }
}

我的問題:我需要將getConversationWith()方法更改為:

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();
}

獲取與給定 user_id 的對話。

有沒有辦法用集合來做到這一點?

預先感謝

你可以像下面那樣完成,但如果你有一個大的數據集,它就不會表現得很好。

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();
    }
}

希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM