This is an interesting question. Does anyone have a solution?
How to Join Multiple Tables with Eloquent Relationships
Hello,
I have Six tables in a sequence and I want to join them with Eloquent relationships. While I am trying to do this Laravel throws an exception as Laravel accepts only one intermediate table in its relationships. Is there any possibility to join more than three tables. Here is my scenario.
Tables:
- Countries Table: id, name
- States Table: id, name, country_id
- Cities Table: id, name, state_id
- Companies Table: id, name, city_id
- Users Table: id, name, company_id
- Booking Table: id, name, user_id, status (Status 1 represents successful booking and 0 represents failure)
Every model has a hasMany or hasManyThrough relationship and belongsTo relationship to and fro. Now I want to get failure bookings from a state. I can achieve this through manual join queries. But I need to access it through eloquent.
Booking Model:
public function user() {
return $this->belongsTo('App\User');
}
User Model:
public function company() {
return $this->belongsTo('App\Company');
}
public function bookings() {
return $this->hasMany('App\Booking');
}
Company Model:
public function city() {
return $this->belongsTo('App\City');
}
public function users() {
return $this->hasMany('App\User');
}
public function bookings() {
return $this->hasManyThrough('App\Booking' , 'App\User');
}
City Model:
public function state() {
return $this->belongsTo('App\State');
}
public function companies() {
return $this->hasMany('App\Company');
}
State Model:
public function country() {
return $this->belongsTo('App\Country');
}
public function cities() {
return $this->hasMany('App\City');
}
Country Model:
public function states() {
return $this->hasMany('App\State');
}
I am able to add hasManyThrough upto companies. So I can only able retrieve bookings of a company.
$company_bookings = App\Company::find(id)->users->bookings;
But, how can I retrieve bookings of a city, state, and country.
Thanks in advance.
As I see it you have three choices:
- Live with the limits of eloquent and have to chain your query through the various models. This might perform slowly depending on the quantity of data. Eloquent is there to make most querying easy, but it won't always produce a simple equivalent in code.
- Write your query using the query builder: https://laravel.com/docs/5.5/queries
- Do a
DB::select()and put all your joins in a single manual query.
I would go with option 2 in this case.
Please or to participate in this conversation.