【发布时间】:2021-02-05 23:23:47
【问题描述】:
我正在编写一个聊天系统,我有以下表格:
chat_conversations: id, name
chat_messages: id, chat_conversation_id, message, deleted_at
chat_message_user: id, chat_message_id, user_id, is_sender, seen, deleted_at
chat_conversation_user: id, user_id, chat_conversation_id, is_owner
我希望将消息分别链接到用户,因此chat_message_user 这样可以单独删除每条消息,但对聊天中的其他用户仍然可见。例如,如果我正在与其他人聊天,而我只想“删除”我自己的对话,我希望对方仍然拥有该聊天记录。
我希望能够查询属于 auth::user 的对话并附加只有他们才能看到的消息(那些 chat_message_user 未被软删除的消息)
Auth::user()->conversations
User模特:
...
public function conversations()
{
return $this->belongsToMany(ChatConversation::class)
->withTimestamps();
}
...
ChatConversation模特:
protected $appends = ['messages'];
public function messages()
{
return $this
->hasMany(ChatMessage::class)
->whereHas('user') //I want whereHas('user') to reference only the user id from the Auth::user()
->get();
}
public function getMessagesAttribute()
{
return $this->messages();
}
...
目前,我正在尝试在我的消息方法上使用 whereHas('user') 但为了让它按我的预期工作,我需要传入一个用户 ID...理想情况下我只想能够从查询开始引用 Auth::user->id...但是如果我在 messages 方法上有一个参数,它将不会追加...
->whereHas('user', function ($query) use ($user_id) {
$query->where('user_id', $user_id);
})
简而言之,我希望对话返回属于当前用户的所有消息,这些消息不会通过 chat_message_user 数据透视表为该特定用户删除。
【问题讨论】:
-
我也在构建一个聊天系统,但我没有考虑只删除一些用户的消息。我会添加一个名为 hide_message_from_user 的新对象,其中包含一对多。然后您可以加载关系并将其设为关系为空的条件。