【问题标题】: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;

}

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 2015-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多