首页 文章

Laravel multiple where子句

提问于
浏览
0

我试图获得购物车中的食物清单以及收藏表 . 我使用以下Query来访问它 . 在条件条款部分,我想检查食物是否在收藏夹表中,它还显示或是否在推车表中也会显示 . 但它无法检查where子句内部是指食品ID在购物车表中,而不是在该用户中 . 所以它应该将cart_id返回为null,但它显示了cart_id,尽管该用户没有添加到他的购物车表中 . 在收藏夹表中也是如此 . 我怎样才能使它正确?

$foods = DB::table('foods')
             ->leftjoin('carts','carts.food_id','foods.id')
             ->leftjoin('favorites','favorites.food_id','foods.id')
             ->select('foods.food_name', DB::raw('carts.id as cart_id'),DB::raw('favorites.id as favorite_id'),'foods.id','foods.display_image','foods.price','foods.category_id','foods.description','foods.restaurant_id' )
             ->where('foods.restaurant_id','=',$request->Input(['restaurant_id']))    
                ->orwhere(function ($query) {
                            $query->where('carts.user_id','=',Auth::user()->id)
                                  ->where('favorites.user_id','=',Auth::user()->id);
                    })  

               ->get();

2 回答

  • 0

    假设您正在查询属于餐馆的食物以及添加到购物车或喜欢它的用户,您在SQL中的条件子句是:

    WHERE restaurant_id=:restaurant_id
        AND (carts.user_id=:user_id OR favorites.user_id=:user_id)
    

    您的laravel条件子句将是:

    ->where('foods.restaurant_id', $request->input('restaurant_id')
    ->where(function ($query) {
        $query->where('carts.user_id', Auth::user()->id)
              ->orWhere('favorites.user_id', Auth::user()->id);
    })
    
  • 0

    试试这个:

    $foods = DB::table('foods')
        ->leftJoin('carts', function($join) {
            $join->on('carts.food_id', 'foods.id')
                ->where('carts.user_id', Auth::id());
        })
        ->leftJoin('favorites', function($join) {
            $join->on('favorites.food_id', 'foods.id')
                ->where('favorites.user_id', Auth::id());
        })
        ->select(...)
        ->where('foods.restaurant_id', $request->input('restaurant_id'))
        ->get();
    

    BTW:列别名不需要 DB::raw()

    ->select('carts.id as cart_id')
    

相关问题