为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

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 关注
  • 117 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号