2017-02-20 114 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