我创建了四个模型,并且正确定义了它们的关系。我没有掌握的是如何在我的情况下使用这些关系。
让我们使用countries
> regions
> cities
> censuses
作为关系的一个人为的例子。我可以在Census
模型中使用此功能获取最近一次的人口普查日期:
public static function getMaxTakenOn($country_id)
{
return \DB::table('regions')
->join('cities', 'cities.region_id', '=', 'region.id')
->join('censuses', 'censuses.city_id', '=', 'cities.id')
->where('regions.country_id', '=', $country_id)
->max('censuses.taken_on');
}
如何重写函数体以使用Eloquent Relations?
答案 0 :(得分:1)
在每个模型中使用hasMany
和自定义字段:
https://laravel.com/docs/5.5/eloquent-relationships
您在Regions模型中的示例,您将需要:
public function cities() {
return $this->hasMany('App\Cities');
}
然后在你的其他模特中继续等等。
完成后,您不需要2个连接,您可以像以下一样访问它们:
$region = new Region();
$region->where('country_id', '=', $country_id)
->max('censuses.taken_on');
echo $region->cities()->censuses()->count();