2 回答

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'?

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();
}
- 2 回答
- 0 關注
- 153 瀏覽
添加回答
舉報