场景-我有3个表>国家、州、城市。城市有州栏,国家有乡土栏,国家没有参考。
城市模型方法
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');
}Problem --我想得到一个国家的城市名单。我怎样才能在乡村模型中创建这样的方法?
public function cities(){
return $this->states()->cities(); //Calling hasMany on builder is not possible.
}类似地,一种从城市模型到国名的方法。
发布于 2016-09-06 13:52:24
若要检索一个国家所有城市的集合,请使用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);
}
}发布于 2016-12-15 09:07:56
国家模式:
<?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();https://stackoverflow.com/questions/35362049
复制相似问题