Laravel 5 - 雄辩的模型 - 3 张系列表


Laravel 5 - eloquent model - 3 tables in series

>场景 - 我有 3 张表>国家、州、城市。城市有状态 id 列,州有国家 id 列,国家没有引用。

城市模型方法

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();