场景: 在一个hasMany
关系,使用with
功能(预先加载),我想内(而不是全部)限制从各行的结果。Laravel的hasMany关系,限制与查询
我下面这个教程(我认为这是实现我从我因此,阅读需要的唯一方法) - 我有一个Model
https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/
- 房间,hasMany
评论。
房型号:
class Room extends Scopes\BaseModel
public function reviews()
{
return $this->hasMany('App\Review');
}
public function latestReviews()
{
return $this->reviews()->latest()->nPerGroup('room_id', 1);
}
作用域/ BaseModel.php:
从网站上的教程直接复制,但namespace App\Scopes;
控制器的使用与命名空间功能:
class Room extends Scopes\BaseModel
$rooms = Room::where('room_types_id', $specialism_id)
->with('latestReviews')
->get();
错误:
RelationNotFoundException in RelationNotFoundException.php line 20: Call to undefined relationship [latestReviews] on model [App\Room].
谢谢,但这两种解决方案限制了评论的总数,而不是每个房间的评论总数。 – Ben
第二个限制集合中每个房间的评论数量 – xhulio
我应该在哪里使用访问方法? – Ben