laravel - 如果急切加载的值具有价值,则仅返回雄辩的结果?
问题描述
我想做的是获取所有对话的列表,这些对话只有一个 latestMessage 并返回一个 JSON 输出。
一个对话有很多消息,但只有一个最新消息:
public function latestMessage()
{
return $this->hasOne(Message::class)->latest();
}
用户模式
public function conversations()
{
return $this->belongsToMany('App\Conversation','conversation_participants', 'user_id', 'conversation_id');
}
对话控制器
public function index()
{
$user = Auth::user();
$user_id = $user->id;
$conversations = $user->conversations()->with(['latestMessage'
//Gets conversations that aren't with the user signed in
,'participants' => function ($query) use ($user_id){
$query->where('user_id', '!=' , $user_id);
}])->orderBy('updated_at','desc')->take('20')->get();
return $conversations;
}
解决方案
你可以试试:
$conversations = $user->conversations()
->has('latestMessage') // <-- limits results to conversations with a latestMessage
->with(['latestMessage','participants' => function ($query) use ($user_id) {
$query->where('user_id', '!=' , $user_id);
}])
->orderBy('updated_at','desc')
->take('20')
->get();
这是文档的相关部分:
https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence
推荐阅读
- java - 输出和解释是什么?
- android - 关于 Ad Mob 插页式广告的问题
- javascript - Firebase 存储中的奇怪行为
- wpf - 在 DataGridColumn 中使用资源中的 ControlTemplate
- javascript - 多次应用替换(使用 Javascript 动态)
- amazon-ec2 - VPN IKE 重新协商导致 Glassfish 中的数据库连接断开
- django - 无法覆盖模型 save()
- php - 完全排除 Woocommerce 中运输的所有邮政信箱变体
- c++ - 错误:对“set_union”的调用没有匹配
- javascript - 为什么我的对象没有将数据填充到图表中?(包括演示)