1

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 ?

1
  • That is totally a different question. Thanks Commented Jun 18, 2016 at 20:14

4 Answers 4

3

Try just using as:

->select('cities.name as city_name', 'provinces.name as province_name', 'countries.name as country_name')
Sign up to request clarification or add additional context in comments.

Comments

0

Would you try with this :

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

I hope it helps you !

2 Comments

No, it is not working. it is replacing all the values with the value of Country Name.
Try without the select clause !
0

ok this is going to be a specific answer learn about realtions in laravel and look at these

class example1 extends Model
    {
      public function examplefunction() {
        return $this->hasMany('App\othermodel', 'id');
    }
}

then use this query

$abc=example1::with('examplefunction')->get();

and there you go just take a look at a laravel relationship by using this u can get combined result

Comments

-2
 $products = User::select('id', 'email', 'first_name', 'last_name','country_code','mobile')->get()->toArray();
       $gaurang = Ticket_Thread::select('body','title','resolv_note')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.