1

我有3個表,如何在Laravel 5中從多個表中獲取特定列?

  1. 國家: ID, 名

  2. 省: ID, 名, COUNTRY_ID

  3. 市: ID, 名, province_id

我在模型中定義的關係如下,

國家型號:

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

省型號:

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

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

市型號:

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

我使用下面的查詢,bu它用國名覆蓋所有的數據。

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

我想從laravel 5中的這些表中獲取城市名稱,省名稱,國家名稱的結果。您能幫我解決嗎?

+0

這完全是一個不同的問題。謝謝 – Hammad

回答

3

儘量只使用as

->select('cities.name as city_name', 'provinces.name as province_name', 'countries.name as country_name') 
+0

謝謝。它解決了我的問題。 – Hammad

0

你試試這個:

$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']); 

我希望它可以幫助你!

+0

不,它不工作。它將用Country Name的值替換所有值。 – Hammad

+0

嘗試不使用select子句! –

0

確定這將是一個明確的答案 瞭解在laravel關係基本概念,並期待在這些

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

然後使用該查詢

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

和你去那裏只是看看通過使用這個u的laravel關係可以得到結合的結果

相關問題