surendrasahi
2 years ago
5647
6
Eloquent

How to Join Multiple Tables with Eloquent Relationships

Posted 2 years ago by surendrasahi

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:

  1. Countries Table: id, name
  2. States Table: id, name, country_id
  3. Cities Table: id, name, state_id
  4. Companies Table: id, name, city_id
  5. Users Table: id, name, company_id
  6. 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.

Please sign in or create an account to participate in this conversation.