You could look over some of these, as this a such a common question:
Get data from 3 tables with relationship
Hello. I'm new in this site and also new in Laravel. Could you please help me with this question?
I have this DB table structure:
-
user
- id
- name
- city_id
-
city
- id
- name
- region_id
-
region
- id
- name
I can get the City name as there is a direct relationship with User table. I do this in the User model with this lines:
public function city()
{
return $this->belongsTo('App\City');
}
Now I'm triying to get the region name related with a user but I can´t.
I tried like this but I think that does not work on that way.
public function region()
{
return $this->belongsTo('App\Region');
}
Also in this way is not working:
DB::table('city') ->join('region', 'region.ide', '=', 'city.region_id') ->get();
A already reviewed the information with Eloquent Relationships but maybe i'm not understanding the concept.
Thanks in advance for your help.
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.
Please or to participate in this conversation.