Reputation: 417
I am struggling to get my head around some relationships.
Below are simplified schema's to help show you what I am trying to achieve:
User model
user_id (integer)
Address Table
user_id (integer)
country_code (integer)
Countries table:
country_code (integer)
country_description (text)
I had a relationship in the User model as follows: The user model has a relationship:
public function addresses() {
return $this->hasMany('App\Address');
}
In the Address model I have a relationship of
public function user() {
return $this->belongsTo('App\User');
}
Now, in my blade template I am able to @foreach through user->addresses and return the country code stored in the address table, such as 'US' or 'GB'
However, I want to be able to display the full country name, which is held in the Countries table.
How and where do I setup a relationship which will still allow me to iterate through the addresses table, but also have a relationship with the Countries table so that I can display the countries->country_description column.?
Any ideas
Regards
James
Upvotes: 2
Views: 2278
Reputation: 1281
In your Address Model:
public function countries()
{
return $this->hasOne('App\Countries', 'country_code');
}
You could then access an $address->countries->country_description;
Upvotes: 3