0

I am using Eloquent to pull users out of my database, and i want to "join" the postal code from my users table with the postal code from my cities table, to retrieve the city name.

Heres a simplified version of my tables:

users => id username password postal_code cities => postal_code city_name 

In my User model i have a method called city() that declares the relationship with my cities table:

public function city() { return $this->hasOne('cities', 'postal_code'); } 

The problem now is when i try to do User::with('city')->find($user_id), the value being passed to the method is the primary key, the id, instead of the postal_code.

So my query ends up being (this is for the user with id 1):

select * from `cities` where `cities`.`postal_code` in ('1') 

Is there someway to specify that i want to pass the postal_code instead?

2 Answers 2

1

There are a few things going on here. This is actually a belongs to relationship because the user holds the value that relates it to the city. The relationship would be better defined like this.

public function city() { return $this->belongsTo('City', 'postal_code'); } 

The user only belongs to one city but the city has many users. In the City model you would have.

public function users() { return $this->hasMany('User', 'postal_code'); } 

Now you will still have problems here because Laravel expects the relationships to use the primary key of the model. In order to get this working you will need to make the postal code the primary key for the City model.

class City extends Eloquent { protected $primaryKey = 'postal_code'; } 

This will effect every other place that you use a primary key with the City model but I think that should be OK given your current structure.

$city = City::find($postal_code); 

I hate to throw a wrench into your plan here but in many places a city will have many postal codes. :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thankyou, that worked! It's a little confusing moving from joining manually, to using an ORM, so guess i got them mixed up.
And about the cities having same postal codes, i have just set the name to the same, so that is not a problem (; Onlt a few cities here in Denmark anyways. And the primary key on here was already the postal code, so that's just fine
1

Since the Relation class uses parent->getKey() (parent is User on your case) this will result in '1'.

I don't think changing the key for User to postal_code is good option ;) So my guess is to give the users table a 'city_id' column and the cities an 'id' column, so things can work as designed.

An other would be not to return a relation, but something like.. return City::wherePostalCode($this->postal_code)->first();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.