2016-04-21 92 views
0

我有三個表是如下:laravel加入三個表

invent_accessory ID,密碼,細節,is_length

invent_price_accessory ID,invent_accessory_id_fk,價格,顏色

invent_price_accessory_length id,invent_accessory_id_fk,price,color

我如何結合這三個表,這樣我可以得到ID,密碼,DETAL,is_length,價格,顏色

我做以下,但它不不返回任何數據:

public function getAccessoryInventPrice(){ 

    $accessory=DB::table('invent_accessory') 
     ->select('invent_accessory.id as accessory_id') 
     ->join('invent_price_accessory','invent_price_accessory.invent_accessory_id_fk','=','invent_accessory.id') 
     ->join('invent_price_accessory_length','invent_price_accessory_length.invent_accessory_id_fk','=','invent_accessory.id') 
     ->get(); 

    return $accessory; 

} 

我在猜測我必須做invent_price_accessoryinvent_price_accessory_length然後加入invent_accessory?我該怎麼做呢?請幫助。

+1

你缺少_fk –

+0

謝謝你指出它。這只是一個打字錯誤。我編輯了我的帖子,但它不能解決我的問題。 – user3810794

回答

0

我的猜測是對的!我能解決這個:

public function getAccessoryInventPrice(){ 


    $data1=\DB::table('invent_price_accessory')->select('accessory_code_id','color_id','rate'); 
    $data2=\DB::table('invent_price_acc_length')->select('accessory_code_id','color_id','rate') 
       ->union($data1); 

    $query= \DB::table(\DB::raw("({$data2->toSql()}) as invent_price")) 

      ->join('invent_accessory','invent_price.accessory_code_id','=','invent_accessory.id') 
      ->join('invent_color','invent_price.color_id','=','invent_color.id') 
      ->select('invent_accessory.id','code','sl_detail','is_length','rate','invent_color.name') 
      ->orderBy('invent_accessory.id','asc') 
      ->get(); 
       return $query; 

}