亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在數據透視表中搜索兩個用戶擁有的行

如何在數據透視表中搜索兩個用戶擁有的行

PHP
慕斯王 2022-10-14 16:06:19
對不起,如果這是一個愚蠢的問題,但我是 Laravel 的新手。我有兩個模型和一個數據透視表:用戶id | name | passwordpublic function conversations(): ?BelongsToMany{  return $this->belongsToMany(Conversation::class)->withTimestamps();}對話idpublic function users(): ?BelongsToMany{  return $this->belongsToMany(User::class)->withTimestamps();}對話用戶id | conversation_id | user_id我創建一個對話并為用戶分配同步,如下所示:$user->conversations()->syncWithoutDetaching($conversation);$targetUser->conversations()->syncWithoutDetaching($conversation);用戶可以有很多對話,對話可以有多個用戶。這很好,但是當我想與兩個特定用戶進行對話時,我不知道利用 ORM 來找到他們各自所在的對話的最佳方式。我目前正在使用下一種方法,該方法有效,但感覺使用 ORM 有更好的方法:/** * Get a conversation by a target user id. * * @param int $targetUserId * @return mixed */public function getConversationByTargetUserId(int $targetUserId){    // Get the current user.    $user = Auth::guard()->user();    // Check the user exists.    if (!$user) {        throw new HttpException(500);    }    /**     * Get all pivot tables where the     * user ID is from the current user.     */    $userConversationIdsArray = DB::table('conversation_user')->where('user_id', $user->id)->pluck('conversation_id');    /**     * Get all pivot tables where the user     * id is equal to the target id, and is     * also owned by the current user. Return     * the first instance that we come across.     */    $targetConversation = DB::table('conversation_user')->where(['conversation_id' => $userConversationIdsArray, 'user_id' => $targetUserId])->first();    /**     * Return the conversation.     */    return Conversation::find($targetConversation->conversation_id);}感謝您的時間 :)
查看完整描述

2 回答

?
BIG陽

TA貢獻1859條經驗 獲得超6個贊

你沒有使用 Eloquent 有什么特別的原因嗎?它可能會讓事情變得更容易。

由于您已經擁有用戶,因此可以這樣做。

$user->conversations()->has('users.id', '=', $targetUserId)->first();

(我沒有測試過這個解決方案,所以我不確定它是否 100% 有效)

此外,您的第一個查詢中可能存在拼寫錯誤。可能是復制粘貼錯誤,可能是錯字。只是確保。

$userConversationIdsArray = DB::table('conversation_user')->where('user_id', $user->id)->pluck('id'); <---- 'id' shouldn't that be 'conversation_id'?


查看完整回答
反對 回復 2022-10-14
?
繁華開滿天機

TA貢獻1816條經驗 獲得超4個贊

他們讓我走上了正軌。以下方法有效:


/**

 * Get a conversation by a target user id.

 *

 * @param int $targetUserId

 * @return mixed

 */

public function getConversationByTargetUserId(int $targetUserId)

{

    // Get the current user.

    $user = Auth::guard()->user();


    // Check the user exists.

    if (!$user) {

        throw new HttpException(500);

    }


    return $user->conversations()->whereHas('users', function ($query) use ($targetUserId) {

        $query->where('users.id', $targetUserId);

    })->first();

}


查看完整回答
反對 回復 2022-10-14
  • 2 回答
  • 0 關注
  • 153 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號