場景: 在一個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