0

如何在 Laravel 5 中将以下查询转换为 eloquent 模型?

    $city = DB::table('cities')
        ->join('provinces', 'cities.province_id', '=', 'provinces.id')
        ->join('countries', 'provinces.country_id', '=', 'countries.id')
        ->select('cities.name as City','provinces.name as Province','countries.name as Country')
        ->where('cities.isDelete', '=', '0')
        ->get();

我的表结构是:

  1. 国家:身份证,姓名

  2. 省份:id、name、country_id

  3. 城市:id、name、province_id

我已经完成了具有 2 个表的 eloquent 模型,但我不知道如何管理 3 个表。PS 我已经在模型中正确定义了我的关系。

4

1 回答 1

0

试试这些代码。有关更多信息,请参阅https://laravel.com/docs/5.2/eloquent-relationships

 //Create this method in city model

public function province()
    {
        return $this->belongsToMany('App\Province');
    }

//Create this method in province model

public function country()
    {
        return $this->belongsTo('App\Country');
    }

现在试试这个查询

$city = DB::table('cities')->with('province','province.country')
        ->where('cities.isDelete', '=', '0')
        ->get();

结果数据将采用嵌套形式

like cities
       -province
         ->country 
于 2016-06-19T12:32:05.243 回答