Laravel sort hasMany Country-> City Relation

时间:2016-03-05 10:34:56

标签: php laravel relationship has-many laravel-5.2

我有以下型号:

国家,乡村翻译,城市,城市翻译

我希望获得某个国家/地区所有城市的列表,但必须按照其名称排序。问题是这些城市名称都在CityTranslation中。

以下是模型定义: 国家:

class Country extends Model {
    protected $fillable = [
        'code', 'latitude', 'longitude', 'currency_id', 'timezone', 'dam_date', 'status',
    ];

public function translations() {

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

}

public function city() {

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

}

}

城市:

class City extends Model {

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

public function translations() {

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

}


public function country() {

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

}

}

CityTranslation:

class CityTranslation extends Model {

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

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

}

目前我得到的城市如下,但没有订购:

$country = $this->country->findOrFail($id);
foreach (City::where('country_id', '=', $id)->get() as $cur) {
    $city_trans = CityTranslation::where(array(['city_id', '=', $cur->id], ['lang', '=', Lang::getLocale()]))->orderBy('name', 'asc')->first();
    $cities_by_country[$cur->id] = $city_trans->name;
}

1 个答案:

答案 0 :(得分:0)

Country模型中,您可以使用以下内容:

public function city()
{
    return $this->hasMany('App\Models\City')->orderBy('name');
}

然后,当您查询Country使用with时,例如:

$countryWithCity = Country::with('city')->findOrFail($id);

因此,$countryWithCity->city将被订购。