如果急切加载的值具有价值,则仅返回雄辩的结果?
Posted
技术标签:
【中文标题】如果急切加载的值具有价值,则仅返回雄辩的结果?【英文标题】:Only return eloquent result if eager loaded value has value? 【发布时间】:2019-03-08 03:54:29 【问题描述】:我想做的是获取所有对话的列表,这些对话只有一个 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;
【问题讨论】:
【参考方案1】:你可以试试:
$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
【讨论】:
以上是关于如果急切加载的值具有价值,则仅返回雄辩的结果?的主要内容,如果未能解决你的问题,请参考以下文章