Question: Laravel nested relationship query


Laravel nested relationship query

Answers 0
Added at 2017-01-02 17:01

Question: How to get best 3 organizations according to column General in Review, together with other related data(User, Address, City, Country, Review, Activity)

PS. Organization has many reviews, and column General is a grade 1-5.

I have tables Organization, User, Review, Activity, Address, City, Country. Tables and relationships:

I also have models for each table and their relationships: Example table organization:

class Organization extends Model     {
protected $table = 'organization';

protected $fillable = ['OrgName'];

public function user() {
    return $this->belongsTo('App\Models\User', 'UserId', 'Id');

public function address() {
    return $this->belongsTo('App\Models\Address', 'AddressId', 'Id');

public function review() {
    return $this->hasMany('App\Models\Review', 'OrganizationId', 'Id');

public function activity() {
    return $this->belongsTo('App\Models\Activity', 'ActivityId', 'Id');

So far I got this:

class OrganizationRepository  {
protected $organization;

function __construct(Organization $organization)
    $this->organization = $organization;

    public function best3() {
    return $this->organization->with(['', 'activity', 'review' => function($query) {
        $query->orderBy('Timestamp', 'desc')->take(1);
    }, 'review.user' ])->where()->take(3)->get(); 
Answers to

Laravel nested relationship query

Source Show
◀ Wstecz