在 Laravel 中,是否可以从 BelongsToMany
关系中预加载“第一个”项目?比如,从该关系中返回一个 Item
,而不是一个 Collection
?
根据我尝试(和阅读)应用 first()
或 limit('1')
或任何其他约束不会返回单个项目
最佳答案
使用 accessor .
我猜你需要像 latest
、first
之类的东西,或者集合中的此类单个项目,所以你可以这样做:
public function items()
{
return $this->belongsToMany(Item::class);
}
public function getLatestItemAttribute()
{
return $this->items->sortByDesc('created_at')->first();
}
然后你可以简单地使用:
$yourModel->latestItem; // single related model OR null
编辑:正如@Hkan 在评论中提到的,上面的代码将导致获取整个集合并对其进行处理。也就是说,您可以使用替代关系对象并直接查询表:
public function getLatestItemAttribute()
{
return $this->items()->latest()->first();
}
但是,通过这种方式,您可以在每次调用 $model->latestItem
时运行查询。结果,您获得了模型的新副本,而不是同一个实例,显然您可以查询数据库任意次数,具体取决于您的用例。
困难但最好的方法是模仿这种关系:
public function getLatestItemAttribute()
{
if (!$this->relationLoaded('latestItem')) {
$this->setRelation('latestItem', $this->items()->latest()->first());
}
return $this->getRelation('latestItem');
}
在这种情况下,$model->latestItem
被视为任何其他单一 关系,一旦加载。也就是说,无论何时调用访问器,它都将是单个实例,并且在使用 push
方法时将被保存。
关于php - Laravel - 在多对多关系中渴望加载单个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35836070/