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?

4

2 回答 2

1

这里发生了一些事情。这实际上是一种归属关系,因为用户持有将其与城市相关联的价值。像这样定义这种关系会更好。

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

用户只属于一个城市,但该城市有很多用户。在城市模型中,您将拥有。

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

现在你仍然会在这里遇到问题,因为 Laravel 期望关系使用模型的主键。为了使这个工作,您需要将邮政编码作为 City 模型的主键。

class City extends Eloquent {

    protected $primaryKey = 'postal_code';

}

这将影响您在 City 模型中使用主键的所有其他地方,但我认为考虑到您当前的结构,这应该没问题。

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

我不想在这里打断你的计划,但在很多地方,一个城市会有很多邮政编码。:)

于 2013-11-14T21:21:17.420 回答
1

由于 Relation 类使用parent->getKey()(在您的情况下,父级是用户),这将导致“1”。

我不认为将 User 的键更改为 postal_code 是一个好选择;)所以我的猜测是给 users 表一个“city_id”列,给城市一个“id”列,这样事情就可以按设计工作了。

另一种是不返回关系,而是类似.. return City::wherePostalCode($this->postal_code)->first();

于 2013-11-13T12:26:49.250 回答