在laravel中一起加入两个查询

时间:2018-03-05 02:53:54

标签: php laravel

我有这个功能:

    public function landings($slug){
        $landing = Landing::where('slug', $slug)->firstOrFail();

    //use to get categories id stored in DB
        $cat = DB::table('landing_categories')->where('landing_id', $landing->id)->get();
        foreach ($cat as $key) {
          $id[] = $key->category_id;
        }

// use to get specifications id and compare it with products that have same specifications id's
        $subs = DB::table('landing_specifications')->where('landing_id', $landing->id)
        ->join('product_subspecification', function ($keys) {
            $keys->on('product_subspecification.subspecification_id', '=', 'landing_specifications.subspecification_id');
        })
        ->join('products', 'products.id', '=', 'product_subspecification.product_id')
        ->get();
    // dd($subs);

// using this to get result of 2 queries above at once
        $prod = DB::table('products')
        ->whereIn('products.category_id', $id)
        ->groupby($subs)
        ->get();
        return view('front.landing', compact('landing', 'prod'));
      }

查询:$cat& $subs按预期工作,并返回我正在寻找的结果。

  

我的问题是如何在$prod查询中绑定这两个?

到目前为止,我可以cat使用whereIn,但是当您看到$subs$prod时,我们都会尝试获取DB::table('products')这是products问题我想。

我得到了这个错误:

  

SQLSTATE [HY093]:参数号无效:混合命名和位置   参数(SQL:select * from products where   category_id->union($subs) in(3,4)group by   `[{" id":1," landing_id":8," s //继续......

PS: 如果我使用->groupby($subs)代替dd($id);,我会得到:

  

方法getBindings不存在。

更新

array:2 [▼ 0 => 3 1 => 4 ]

dd($subs);

Collection {#721 ▼ #items: array:5 [▼ 0 => {#710 ▼ +"id": 1 +"landing_id": 8 +"subspecification_id": 1 +"product_id": 1 +"title": "product one" +"slug": "product-one" +"imageOne": "product-1517990897.jpg" +"imageTwo": "product-1517990897.png" +"short_description": "<p>this is first testing product</p>" +"description": "<p>this is first testing product this is first testing product this is first testing product this is first testing product this is first testing product this is ▶" +"price": "10000000" +"meta_description": null +"meta_tags": null +"arrivalDays": "2" +"height": "100" +"weight": "1" +"lenght": "100" +"width": "100" +"sku": "1985629" +"stock": "16" +"status_id": 1 +"brand_id": 2 +"category_id": 1 +"subcategory_id": 2 +"created_at": "2018-02-07 15:05:00" +"updated_at": "2018-02-28 14:16:46" } 1 => {#716 ▶} 2 => {#714 ▶} 3 => {#720 ▶} 4 => {#718 ▶} ] }

$cat

PS:当我将$subs1放在一起时,它应该将结果减少到===false,这是我保存的y数据的正确答案。

1 个答案:

答案 0 :(得分:0)

解决

我将我的$subs$prod混合在一起,如下所示,它完美地运作:

$prod = DB::table('landing_specifications')->where('landing_id', $landing->id)
    ->join('product_subspecification', function ($keys) {
        $keys->on('product_subspecification.subspecification_id', '=', 'landing_specifications.subspecification_id');
    })
    ->join('products', 'products.id', '=', 'product_subspecification.product_id')
    ->whereIn('products.category_id', $id)
    ->groupby('products.id')
    ->get();