php - Laravel Eager Load and Group Multiple Joins on Pivot -


i have pivot table thats used join 2 other tables have many relations per hotel_id. there way can eagerload relationship pulls results both tables in 1 relationship? raw sql query, works correctly when using belongstomany order off.

amenities pivot table

id hotel_id  distance_id type_id 

distance table

id name 

type table

id name 

raw query (this works fine)

select * amenities  left join distance d on a.distance_id = d.id  left join type t on a.type_id = t.id a.hotel_id = ? 

my "hotels" model using belongstomany so

public function distance() {     return $this->belongstomany('distance', 'amenities', 'hotel_id', 'distance_id'); } public function type() {     return $this->belongstomany('type', 'amenities', 'hotel_id', 'type_id'); } 

this outputs collection, not grouped correctly. need loop these select fields side side entered in pivot table, user can select "type" , "distance", order off when using collection. raw query above outputs correctly.

hotels::where('id','=','200')->with('distance', 'type')->take(5)->get(); 

ok solved it. apparently can use orderby on pivot table. incase else has issue did on both relationships.

public function distance() {     return $this->belongstomany('distance', 'amenities', 'hotel_id', 'distance_id')->withpivot('id')->orderby('pivot_id','desc'); } public function type() {     return $this->belongstomany('type', 'amenities', 'hotel_id', 'type_id')->withpivot('id')->orderby('pivot_id','desc'); } 

it's not great practice include other query building steps in relationship methods on models. relationship method should define relationship, nothing else. cleaner method apply eager load constraints. (scroll down bit) consider following.

hotels::where('id', 200)->with(array(     'distance' => function ($query)     {         $query->withpivot('id')->orderby('pivot_id','desc');     },     'type' => function ($query)     {         $query->withpivot('id')->orderby('pivot_id','desc');     }, ))->take(5)->get(); 

if find eagerly loading relationship in way often, consider using scopes keep things dry. end result allow this.

hotels::where('id', 200)->withordereddistance()->withorderedtype()->take(5)->get(); 

p.s. models should singular. hotel, not hotels. model represents single record.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -