laravel加入三张桌子

时间:2016-04-21 08:34:00

标签: laravel join union

我有三个表如下:

invent_accessory ID,代码,细节,is_length

invent_price_accessory ID,invent_accessory_id_fk,价格,颜色

invent_price_accessory_length ID,invent_accessory_id_fk,价格,颜色

如何组合这三个表,以便我可以获得 id,code,detal,is_length,price,color

我已完成以下操作,但它不会返回任何数据:

 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_accessory invent_price_accessory_length 之间进行联合,然后加入 invent_accessory ?我该怎么做呢?请帮助。

1 个答案:

答案 0 :(得分: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;

 }