lundi 2 janvier 2017

Laravel nested relationship query

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(['address.city.country', 'activity', 'review' => function($query) {
        $query->orderBy('Timestamp', 'desc')->take(1);
    }, 'review.user' ])->where()->take(3)->get(); 
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire