我有一對一聊天簡單表,其中訊息存盤從用戶 id 到用戶 id。這是架構。

我通過將 from_user_id 匹配與登錄用戶或 to_user_id 匹配來檢索兩個用戶之間的對話
->where(function($q) use($user_id) {
$q->where('from_user_id', $user_id)
->orWhere('to_user_id', $user_id);
})
現在我想要登錄用戶和其他用戶之間的獨特對話。我試過
->groupBy('from_user_id', 'to_user_id')
但它回傳記錄 id : 1 和 6,因為它存盤為 65 - 66 和 66 - 65。
因此,我可以通過獨特的對話進行分組并僅獲得一條記錄。或者我需要將表的模式更改為對話和對話訊息。
請指導我。謝謝。
uj5u.com熱心網友回復:
我建議添加一個對話模型。您基本上需要每個用戶到用戶關系(以及其中的所有訊息)的唯一識別符號,而對話模型將是實作這一目標的最簡潔方式。
話雖如此,有一些聰明的方法可以在沒有額外模型的情況下做你想做的事情。由于您知道登錄用戶的 ID,您可以將回呼傳遞給 Collection 的 groupBy 方法,該方法根據不是登錄用戶的 ID 進行分組。例如:
->where(function($query) {
$query->where('from_user_id', $user_id)
->orWhere('to_user_id', $user_id)
})
// So the messages appear in order.
->orderByDesc('created_at')
->get()
->groupBy(function($item) use ($user_id) {
// If the message was sent by the user, it groups on the recipient's ID.
// If the message was received by the user, it groups on the sender's ID.
return $item->from_user_id == $user_id ? $item->to_user_id : $item->from_user_id;
});
此示例不考慮用戶向自己發送訊息(這在您的系統中可能是可能的),因此可能需要進行微調。
uj5u.com熱心網友回復:
最近,我為我的公司撰寫了一個聊天系統。我嘗試了許多模式,但最終找到了最好的模式。我可以和你分享。

此模式可能由多個表組成,并會迫使您發送更多請求。但是在這種結構中,您將能夠輕松處理所有任務。這是模型和控制器結構:
聊天訊息:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ChatMessage extends Model
{
use HasFactory;
public $table = "chat_messages";
protected $fillable = ['chat_id', 'user_id','content'];
public function chat()
{
return $this->belongsTo(ChatUser::class, 'chat_id', 'id');
}
public function user()
{
return $this->belongsTo(User::class);
}
}
聊天用戶:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ChatUser extends Model
{
use HasFactory;
public $table = "chat_users";
protected $fillable = ['user_id_from', 'user_id_to','last_activity'];
protected $dates = ['last_activity'];
public function user_from()
{
return $this->belongsTo(User::class, 'user_id_from', 'id');
}
public function user_to()
{
return $this->belongsTo(User::class, 'user_id_to', 'id');
}
public function messages()
{
return $this->hasMany(ChatMessage::class, 'chat_id', 'id')->latest('id')->take(15);
}
}
聊天控制器:
public function index()
{
$chats = ChatUser::has('messages')
->where('user_id_from', $this->user->id)
->orWhere(function ($query) {
$query->where('user_id_to' , $this->user->id);
})
->with(['user_to','user_from'])
->orderBy('last_activity', 'DESC')
->get();
return $this->successResponse(new ChatCollection($chats));
}
如果您有任何問題,請隨時提出。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/326304.html
標籤:php mysql 拉拉维尔 数据库设计 laravel-8
上一篇:我需要獲得最多點贊的5個帖子
下一篇:SHA512轉字串,PHP
