从与“懒惰的渴望加载"的关系中返回第一个元素[Laravel 5.2] [英] Return first element from relation with `Lazy Eager Loading` [Laravel 5.2]
本文介绍了从与“懒惰的渴望加载"的关系中返回第一个元素[Laravel 5.2]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的关系:
public function message()
{
return $this->hasMany('Engine\Message');
}
在我的Conversation
模型中.
对于每次对话,我都需要获取最新消息.
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?
推荐答案
如建议在急切加载中不要使用first()
或get()
,您应该在模型中创建新的关系.
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');
}
对"pmall"表示敬意
kudos to 'pmall'
这篇关于从与“懒惰的渴望加载"的关系中返回第一个元素[Laravel 5.2]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文