我有一个聊天应用程序,我需要使用 eloquent ORM 过滤那些在组上一条消息中有附件 [s] 的用户对话。我有以下数据库表/模型:
这种过滤的算法不是问题 - 获取用户(因为我需要特定的用户组)和他的组,找到所有组消息,按创建日期按降序对它们进行排序,然后取前一个。然后检查此消息在“附件”表中是否有任何记录。显然,我确实在各自的模型中定义了所有关系。现在我有这个代码,但它返回在任何消息中包含附件的所有组。此外,我需要按最后一条消息“created_at”日期对查询进行排序。
return $user->user_groups()->whereHas('group', function($query) {
$query->whereHas('messages', function ($query) {
$query->whereHas('attachments');
});
})->with('group')->latest()->paginate($this->group->getPerPage());
编辑。
class User
{
public function messages()
{
return $this->hasMany('App\Models\Message');
}
public function user_groups()
{
return $this->hasMany('App\Models\GroupUser');
}
}
class Message
{
public function attachments()
{
return $this->hasMany('App\Models\Attachment');
}
public function author()
{
return $this->belongsTo('App\Models\User');
}
public function group()
{
return $this->belongsTo('App\Models\Group');
}
}
class Attachment
{
public function message()
{
return $this->belongsTo('App\Models\Message');
}
}
class GroupUser
{
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function group()
{
return $this->belongsTo('App\Models\Group');
}
}
class Group()
{
public function messages()
{
return $this->hasMany('App\Models\Message');
}
public function group_users()
{
return $this->hasMany('App\Models\GroupUser');
}
}
添加groups
与User
模型的关系:
public function groups() {
return $this->belongsToMany('App\Models\Group');
}
然后试试这个:
$user->groups()
->select('groups.*')
->join('messages', function($join) {
$join->on('groups.id', 'messages.group_id')
->where('created_at', function($query) {
$query->selectRaw('max(created_at)')
->from('messages')
->where('group_id', DB::raw('groups.id'));
});
})
->whereExists(function($query) {
$query->from('attachments')
->where('attachments.message_id', DB::raw('messages.id'));
})
->orderByDesc('messages.created_at')
->paginate($this->group->getPerPage());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句