samedi 18 juin 2016

How to fetch specific columns from multiple tables in Laravel 5?

I have 3 tables,

  1. Country: id, name

  2. Province: id, name, country_id

  3. City: id, name, province_id

I have defined relationships in Model as follows,

Country Model:

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

Province Model:

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

        public function Cities()
        {
            return $this->hasMany('App\City');
        }

City Model:

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

I am using the below query, but it overwrites all the data with Country name.

    $city = DB::table('cities')
        ->join('provinces', 'cities.province_id', '=', 'provinces.id')
        ->join('countries', 'provinces.country_id', '=', 'countries.id')
        ->select('cities.name','provinces.name','countries.name')
        ->get();

I want to fetch a result of only City Name, Province Name, Country Name from these tables in laravel 5. Can you help me with that ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire