0
votes

How to convert the following query to eloquent model in Laravel 5?

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

My table structures are:

  1. Country: id, name

  2. Province: id, name, country_id

  3. City: id, name, province_id

I've done working with the eloquent model with 2 tables but I don't know how to manage 3 tables. P.S. I have properly defined my relationships in model.

1

1 Answers

0
votes

Try these codes. For more info refer 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');
    }

Now Try this query

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

The resulted data will be in nested form

like cities
       -province
         ->country