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 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探