【问题标题】:How to get all country with city and state in Laravel Database如何在 Laravel 数据库中获取所有国家与城市和州
【发布时间】:2019-09-01 17:42:57
【问题描述】:

我有 3 张表 Country 、 State 和 City 它们是相互关联的,就像每个州都有一个国家,每个城市都有一个州 我想知道我是否可以在我的 laravel 应用程序中获得所有国家的所有数据,他们的州和城市也充满了关系。我想知道是否有任何工厂库如果是的话???

【问题讨论】:

标签: database laravel


【解决方案1】:

你可以在它们之间建立关系。

国家模式:

public function states(){
     return $this->hasMany(State::class);
}

public function statesWithCities(){
     return $this->states()->with('cities');
}

状态模型:

public function cities(){
     return $this->hasMany(City::class);
}

public function country(){
     return $this->belongsTo(Country::class);
}

城市模型:

public function state(){
     return $this->belongsTo(State::class);
}

您可以使用以下代码获取所有国家、州、城市:

Country::latest()->with('statesWithCities')->get()

【讨论】:

    猜你喜欢
    • 2011-03-23
    • 2013-02-08
    • 2019-05-27
    • 2013-11-13
    • 1970-01-01
    • 2017-09-25
    • 2017-09-02
    • 2017-10-20
    • 2011-01-14
    相关资源
    最近更新 更多