如何在数据透视表中搜索两个用户拥有的行

对不起,如果这是一个愚蠢的问题,但我是 Laravel 的新手。


我有两个模型和一个数据透视表:


用户


id | name | password


public function conversations(): ?BelongsToMany

{

  return $this->belongsToMany(Conversation::class)->withTimestamps();

}

对话


id


public 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);

}

感谢您的时间 :)


慕斯王
浏览 118回答 2
2回答

BIG阳

你没有使用 Eloquent 有什么特别的原因吗?它可能会让事情变得更容易。由于您已经拥有用户,因此可以这样做。$user->conversations()->has('users.id',&nbsp;'=',&nbsp;$targetUserId)->first();(我没有测试过这个解决方案,所以我不确定它是否 100% 有效)此外,您的第一个查询中可能存在拼写错误。可能是复制粘贴错误,可能是错字。只是确保。$userConversationIdsArray&nbsp;=&nbsp;DB::table('conversation_user')->where('user_id',&nbsp;$user->id)->pluck('id');&nbsp;<----&nbsp;'id'&nbsp;shouldn't&nbsp;that&nbsp;be&nbsp;'conversation_id'?

繁华开满天机

他们让我走上了正轨。以下方法有效:/**&nbsp;* Get a conversation by a target user id.&nbsp;*&nbsp;* @param int $targetUserId&nbsp;* @return mixed&nbsp;*/public function getConversationByTargetUserId(int $targetUserId){&nbsp; &nbsp; // Get the current user.&nbsp; &nbsp; $user = Auth::guard()->user();&nbsp; &nbsp; // Check the user exists.&nbsp; &nbsp; if (!$user) {&nbsp; &nbsp; &nbsp; &nbsp; throw new HttpException(500);&nbsp; &nbsp; }&nbsp; &nbsp; return $user->conversations()->whereHas('users', function ($query) use ($targetUserId) {&nbsp; &nbsp; &nbsp; &nbsp; $query->where('users.id', $targetUserId);&nbsp; &nbsp; })->first();}
打开App,查看更多内容
随时随地看视频慕课网APP