对不起,如果这是一个愚蠢的问题,但我是 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);
}
感谢您的时间 :)
BIG阳
繁华开满天机