dtcaw02086 2016-02-12 11:57
浏览 43
已采纳

Laravel 5 - 雄辩模型 - 3个系列表

Scenario - I have 3 tables > Country, State, City. City have stateid column, State have countryid column, country have no reference.

City Model methods

public function state(){ 
    return $this->belongsTo('App\State', 'stateid');
}

State Model methods

public function country(){
    return $this->belongsTo('App\Country', 'countryid');
}
public function cities(){
    return $this->hasMany('App\City', 'stateid');
}

Country Model methods

public function states()
{
    return $this->hasMany('App\State', 'countryid');
}

Problem - I want to get the list of cities in a country. How can I create a method in Country Model like this? -

public function cities(){
    return $this->states()->cities(); //Calling hasMany on builder is not possible.
}

Similarly, a method to country name from city model.

  • 写回答

2条回答 默认 最新

  • doutu3352 2016-09-06 13:52
    关注

    To retrieve a Collection with all cities in a Country, use the hasManyThrough method:

    <?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);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱