如果渴望加载的值有价值,是否只返回雄辩的结果?

时间:2018-10-03 00:43:50

标签: laravel eloquent relationship

我想做的是获取所有仅包含了最新消息的对话列表,并返回JSON输出。

一次对话有很多消息,但只有一条最新消息:

public function latestMessage()
{
    return $this->hasOne(Message::class)->latest();
}

用户模式

public function conversations()
{
    return $this->belongsToMany('App\Conversation','conversation_participants', 'user_id', 'conversation_id');
} 

ConversationsController

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 个答案:

答案 0 :(得分:2)

您可以尝试:

$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