Laravel 5 - eloquent 模型 - 3 个表系列
Laravel 5 - eloquent model - 3 tables in series
场景 - 我有 3 个表 > 国家、州、城市。 City 有 stateid 列,State 有 countryid 列,country 没有参考。
城市模型方法
public function state(){
return $this->belongsTo('App\State', 'stateid');
}
状态模型方法
public function country(){
return $this->belongsTo('App\Country', 'countryid');
}
public function cities(){
return $this->hasMany('App\City', 'stateid');
}
国家模型方法
public function states()
{
return $this->hasMany('App\State', 'countryid');
}
问题 - 我想获取一个国家的城市列表。我怎样才能在这样的国家模型中创建一个方法? -
public function cities(){
return $this->states()->cities(); //Calling hasMany on builder is not possible.
}
同理,从城市模型中提取国名的方法。
要检索包含某个国家/地区所有城市的集合,请使用 hasManyThrough 方法:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
public $timestamps = false;
public function states()
{
return $this->hasMany(State::class);
}
public function cities()
{
return $this->hasManyThrough(City::class, State::class);
}
}
国家模式:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country_master extends Model
{
public function city_state_data()
{
return $this->belongsToMany('App\State_master','city_masters');
}
}
调用模型:
<?php
$data=Country_master::find(1)->city_state_data()->select('city_name','state_name')->get();
场景 - 我有 3 个表 > 国家、州、城市。 City 有 stateid 列,State 有 countryid 列,country 没有参考。
城市模型方法
public function state(){
return $this->belongsTo('App\State', 'stateid');
}
状态模型方法
public function country(){
return $this->belongsTo('App\Country', 'countryid');
}
public function cities(){
return $this->hasMany('App\City', 'stateid');
}
国家模型方法
public function states()
{
return $this->hasMany('App\State', 'countryid');
}
问题 - 我想获取一个国家的城市列表。我怎样才能在这样的国家模型中创建一个方法? -
public function cities(){
return $this->states()->cities(); //Calling hasMany on builder is not possible.
}
同理,从城市模型中提取国名的方法。
要检索包含某个国家/地区所有城市的集合,请使用 hasManyThrough 方法:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
public $timestamps = false;
public function states()
{
return $this->hasMany(State::class);
}
public function cities()
{
return $this->hasManyThrough(City::class, State::class);
}
}
国家模式:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country_master extends Model
{
public function city_state_data()
{
return $this->belongsToMany('App\State_master','city_masters');
}
}
调用模型:
<?php
$data=Country_master::find(1)->city_state_data()->select('city_name','state_name')->get();