2017-02-20 461 views
0

場景: 在一個hasMany關係,使用with功能(預先加載),我想內(而不是全部)限制從各行的結果。Laravel的hasMany關係,限制與查詢

我下面這個教程(我認爲這是實現我從我因此,閱讀需要的唯一方法) - 我有一個Modelhttps://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].

回答

0

這樣做有2種方式。第一個更像是:

Room::with(['reviews' => function ($q) { 
       $q->where('*CONDITION IF NEEDED*')->orderBy('created_at', 'desc')->take(1); 
      }])->where('room_types_id', $specialism_id)->get(); 

第二種方法是使用訪問器。

public function getLatestReviewAttribute(){ 
    return Review::where('room_id', $this->attributes['id'])->orderBy('created_at','desc')->take(1)->get(); 
} 

,您可以通過使用$room->latest_review->review_column_name; 當你的控制器上你可以做Room::all();訪問你的看法;

+0

謝謝,但這兩種解決方案限制了評論的總數,而不是每個房間的評論總數。 – Ben

+0

第二個限制集合中每個房間的評論數量 – xhulio

+0

我應該在哪裏使用訪問方法? – Ben