简体   繁体   中英

Laravel hasMany relationship, limit with query

Scenario: On a hasMany relationship, using the with function (for eager loading), I want to limit the results from each of the rows within (instead of the total).

I am following this tutorial (as I think it's the only way to achieve what I need from what I've read on SO) - https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/

I have a Model - Room that hasMany Reviews.

Room Model:

class Room extends Scopes\BaseModel

   public function reviews()
    {
        return $this->hasMany('App\Review');
    }

    public function latestReviews()
    {
        return $this->reviews()->latest()->nPerGroup('room_id', 1);
    }

Scopes/BaseModel.php:

Direct copy from the website's tutorial, but with the namespace of namespace App\\Scopes;

Controller using the with function:

class Room extends Scopes\BaseModel

$rooms = Room::where('room_types_id', $specialism_id)
            ->with('latestReviews')
            ->get();

Error:

RelationNotFoundException in RelationNotFoundException.php line 20: Call to undefined relationship [latestReviews] on model [App\\Room].

There are 2 ways of doing this. the first one is more like:

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

The second way is using accessors.

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

and you can access it on your view by using $room->latest_review->review_column_name; While on your controller you can just do Room::all(); ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM