【问题标题】:Laravel Relationships recursiveLaravel 关系递归
【发布时间】:2016-03-07 20:29:44
【问题描述】:

我有 3 个模型:

城市:

protected $fillable = [
    'name', 'latitude', 'longitude', 'code', 'country_id', 'status', 'weather_code',
];

public function translations() {

    return $this->hasMany('App\Models\CityTranslation');

}

public function country() {

    return $this->hasMany('App\Models\Country');

}

城市翻译

protected $fillable = [
    'name', 'lang', 'city_id',
];

public function city() {
    return $this->hasOne('App\Models\City', 'id', 'city_id');
}

国家

protected $fillable = [
    'code', 'latitude', 'longitude', 'currency_id', 'timezone', 'dam_date', 'status',
];

public function city() {

    return $this->hasMany('App\Models\City');

}

我的问题是,当我浏览我的 CityTranslations 并显示所选语言的城市名称时,我还想显示有关城市及其国家/地区的信息。

调用 $cityTranslation->city->longitude 没有问题,但是当我调用 $cityTranslation->city->country->code 时,它​​给了我一个 MySQL 错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'countries.city_id' in 'where clause' (SQL: select * from `countries` where `countries`.`city_id` = 4439 and `countries`.`city_id` is not null) 

如何建立递归关系?

【问题讨论】:

  • 为什么在城市和国家之间有一对多?一个城市可以有多个国家? oO 因此,它试图在国家/地区找到 city_id...

标签: php mysql laravel relationship laravel-5.2


【解决方案1】:

试试

$cityTranslation = \App\CityTranslation::with('city.country')->get();

如果您想获得所有城市翻译及其相关的城市和国家/地区。您可以循环并获取国家/地区代码。

如果你只想选择一个城市翻译和它相关的项目你可以做

$cityTranslation = \App\CityTranslation::with('city.country')->find($id);

改变这个(在你的城市模型中)

public function country() {

    return $this->hasMany('App\Models\Country');

}

public function country() {

    return $this->belongsTo('App\Models\Country');

}

因为一个国家可以有很多城市,每个城市都必须属于一个国家

【讨论】:

  • 感谢 oseintow,它可以按我的意愿工作,但是如果我转到城市表单,我会收到一个错误,不幸的是我不知道如何找到我们的问题所在:C:\xampp 中的 BadMethodCallException \htdocs\laravel\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php 第 2161 行:调用未定义的方法 Illuminate\Database\Query\Builder::city()
  • 我发现了问题。实际上只有将 City 模型中的 country() 方法更改为 belongsTo 就足够了:)
猜你喜欢
  • 2014-12-26
  • 2022-01-21
  • 2020-06-12
  • 2018-07-05
  • 2020-11-03
  • 2020-11-09
  • 2019-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多