Search code examples
laraveleloquentrelationships

Laravel Eloquent Relationships - 3 tables, one of which is a lookup table


I am struggling to get my head around some relationships.

  1. I have a Model called User (just stores Users)
  2. A model called Addresses (stores all the addresses a user might have)
  3. A model called Countries (a lookup list of country codes and descriptions)

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


Solution

  • In your Address Model:

    public function countries()
    {
        return $this->hasOne('App\Countries', 'country_code');
    }
    

    You could then access an $address->countries->country_description;