首页 > 解决方案 > 如果急切加载的值具有价值,则仅返回雄辩的结果?

问题描述

我想做的是获取所有对话的列表,这些对话只有一个 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;

}

标签: laraveleloquentrelationship

解决方案


你可以试试:

$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


推荐阅读