我想创建一个聊天系统,我可以列出特定2人之间的所有聊天
我有2个表users
和chats
我的聊天记录表有3列 - user_id
,friend_id
和chat
我的User.php
模型文件就像这样
public function chats() {
return $this->hasMany('App\Chat');
}
例如:
我想在不改变对话顺序的情况下列出用户1和3之间的所有聊天
我可以通过执行$chats = Auth::user()->chats->where('friend_id', '=', $id);
来完成它,但这只会给认证(用户1或3)用户聊天。但我希望他们两人之间的对话。
所以我找到了另一种方法来做到这一点
$first = Chat::all()->where('user_id', '=', Auth::user()->id)->where('friend_id', '=', $id);
$second = Chat::all()->where('user_id', '=', $id)->where('friend_id', '=', Auth::user()->id);
$chats = $first->merge($second);
但这种方式存在一些问题。这不会以正确的顺序进行聊天。我认为不可能正确订购。
所以我的问题是如何轻松地以正确的顺序列出两个人之间的对话?
如果您想了解有关我的问题的更多详细信息,您可以问一下。
答案 0 :(得分:2)
您应该能够在一个带有参数分组的查询中执行此操作,而不是执行两个单独的查询然后合并它们。
Chat::where(function ($query) use ($id) {
$query->where('user_id', '=', Auth::user()->id)
->where('friend_id', '=', $id);
})->orWhere(function ($query) use ($id) {
$query->where('user_id', '=', $id)
->where('friend_id', '=', Auth::user()->id);
})->get();
此可能也会以正确的顺序返回结果,因为没有指定任何排序条件,数据库通常会按插入顺序返回行。但是,如果没有在聊天表中添加某些内容(按时间戳或自动增量ID),则无法保证它。
答案 1 :(得分:2)
首先,在过滤之前不应该all()
。这很糟糕,因为获取所有表数据,然后在PHP中进行过滤。
你应该考虑这样做:
在您的迁移中:
Schema::create("chat", function (Blueprint $table) {
//Other creation lines
$table->timestamps();
})
然后在你的聊天模型中:
public function scopeInvolvingUsers($query, $userId,$friendId) {
return $query->where([ ["user_id",$userId],["friend_id",$friendId] ])
->orWhere([ ["user_id",$friendId],["friend_id",$userId] ]);
}
然后您可以执行以下操作:
$chats = Chat::involvingUsers(\Auth::id(),$otherId)->latest()->get();
请注意,latest
或earliest
要求timestamps
出现在桌面上。
答案 2 :(得分:1)
试试这个
$first = Chat::all()->where('user_id', '=', Auth::user()->id)
->where('friend_id', '=', $id)->get();
$second = Chat::all()->where('user_id', '=', $id)
->where('friend_id', '=', Auth::user()
->id)->get();
$chats = $first->merge($second)
->sortBy('created_at');//created_at is timing added change if other
答案 3 :(得分:1)
我将在聊天表中添加时间戳,以确保订单。 要将时间戳添加到聊天表中,只需添加
$table->timestamps();
您可以选择与用户相关的聊天,并按created_at对其进行排序。 在laravel 5.3+中使用
Chats::where(['user_id', '=', Auth::id()], ['friend_id', '=', $id])->orWhere(['user_id', '=', $id], ['friend_id', '=', Auth::id()])->sortBy('created_at');
答案 4 :(得分:0)
Chat::whereIn('user_id', [$id, Auth->user()->id])
->whereIn('friend_id', [$id, Auth->user()->id])->get();