Support the ongoing development of Laravel.io →
posted 7 years ago
Last updated 2 years ago.
0

In your City Model add

public function region()
{
    return $this->belongsTo('App\Region');
}

You can access the region like

User::with('city.region')->get();
Last updated 7 years ago.
0

I was abble to fix it with the help of one friend.

Finally I'm getting the data from one user, in my controller using something like:

$user = \DB::table('user') ->select( 'user.id', 'user.name', 'city.name as city_name', 'region.name as region_name') ->leftJoin('city', 'user.city_id', '=', 'city.id') ->leftJoin('region', 'city.region_id', '=', 'region.id') ->where('operator.id', '=', $id)->first();

Thanks for try to help me.

0
model user
----------
...
// add this
public function city_master()
{
    return $this->belongsTo('App\City', 'city_id');
}
...


model city
----------
...
// add this
public function user_master()
{
    return $this->hasMany('App\User', 'city_id');
}

public function region_master()
{
    return $this->belongsTo('App\Region', 'region_id');
}
...


model region
------------
...
// add this
...
public function city_master()
{
    return $this->hasMany('App\City', 'region_id');
}

so you can call all relationship data

// for user

$model = User::get();

foreach ( $model as $key => $value ) {
    print_r( $value->city_master )
    print_r( $value->city_master->region_master )
}


// for city

$model = City::get();

foreach ( $model as $key => $value ) {
    print_r( $value->region_master )
    print_r( $value->user_master )
}


// for region

$model = Region::get();

foreach ( $model as $key => $value ) {
    print_r( $value->city_master )
    print_r( $value->city_master->user_master )
}
Last updated 7 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.