Return first element from relation with `Lazy Eager Loading` [Laravel 5.2]

假装没事ソ 提交于 2020-03-06 03:08:08

问题


I have relation like this:

public function message()
{
   return $this->hasMany('Engine\Message');
}

inside my Conversation model.

and for each conversation I need to get last message.

Here is what I tried, but this will get only one message for first conversation but will not get message from other conversations...

$con = Conversation::all();

$con->load(['message' => function ($q) use ( &$mess ) {
                $mess = $q->first();
            }]);

return $con;

I don't wana query for each record... Anyone know how to solve this problem?


回答1:


As suggested here!

Don't use first() or get() in eager loadings you should create a new relationship in the model.

The model would look something like this...

public function message()
{
return $this->hasOne('Engine\Message');
}

kudos to 'pmall'




回答2:


Try

$con = Conversation::all();
$con->load(['message' => function ($q) use ( &$mess ) {
                $q->orderBy('created_at', 'desc')->take(1);
                // or if you don't use timestamps
                // $q->orderBy('id', 'desc')->take(1)
            }]);
return $con;


来源:https://stackoverflow.com/questions/38083504/return-first-element-from-relation-with-lazy-eager-loading-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!