1. 程式人生 > >laravel根據取中間表資料進行查詢

laravel根據取中間表資料進行查詢

存在限制條件不在顯示錶中,在關聯的中間表中,提取中間表資料進行搜尋查詢:

    public function index(Request $request)
    {
        $where = function ($query) use ($request) {
            if ($request->has('name') and $request->name != '') {
                $search = "%" . $request->name . "%";
                $query->where('name', 'like', $search);
            }//本表查詢

            if ($request->has('category_id') and $request->category_id != '-1') {
                $product_id=DB::table('category_product')->where('category_id',$request->category_id)->pluck('product_id');//取中間表資料
                if(count($product_id)>0)
                {
                    $query->where('id',$product_id);
                }else{
                    $query->where('id',-1);
                }
            }

        };
        $products = Product::with('categories', 'brand')->where($where)->get();
//        return $products;
        return view('admin.shop.product.index')->with('products', $products);
    }