Pankaj
Pankaj

Reputation: 229

Laravel eloquent relationship fetch records upto third level of relationship

I have users table which has a hasOne relationship with vendordetails table.

class User extends Authenticatable
{
    public function vendor_details() {
        return $this->hasOne('App\Vendordetail');
    }
}

On the other side vendordetails table contains country_id, state_id and city_id and has relationship of belongsTo with Country, State and City model.

Vendordetail.php model is:-

class Vendordetail extends Model
{
    public $timestamps = false;

    public function this_country(){
        return $this->belongsTo('App\Country', 'country_id');
    }

    public function this_state(){
        return $this->belongsTo('App\Country', 'state_id');
    }

    public function this_city(){
        return $this->belongsTo('App\Country', 'city_id');
    }

}

How can i fetch records of country, state and city if i query on users table.

$user = User::with('vendor_details')->first();

In this query it only finds the result of vendordetails table, i also wants country, state and city.

Thanks

Upvotes: 2

Views: 1780

Answers (1)

Chintan7027
Chintan7027

Reputation: 7615

To access nested relationship

$user = User::with(['vendor_details.this_state','vendor_details.this_country','vendor_details.this_city'])->first();

Upvotes: 9

Related Questions