Home > Enterprise >  Laravel Join If Column Value Not Null
Laravel Join If Column Value Not Null

Time:04-10

$products = ModelsProduct::leftJoin('discounts','discounts.product_id','=','products.id')->leftJoin('categories','categories.id','=','products.category_id')->where('products.status','=','PUBLISHED')->where(function($query){
       if($query->first('discounts.withCode') == 'FALSE'){
             $query = $query->select('discount.discount');
       }
});

I try this method. I want to select discount if withCode value False. I try in where clause but in this method, if not false; I can't access product. I want to select discount if withCode table FALSE. Else, I don't want to select it

CodePudding user response:

I solved with this codes;

$products = ModelsProduct::leftJoin('discounts',function($query){
            $query->on('discounts.product_id','=','products.id')->where('discounts.withCode','=','FALSE');
        })->leftJoin('categories','categories.id','=','products.category_id')->where('products.status','=','PUBLISHED');

CodePudding user response:

Hey mate you can have multiple where statements in the clause so why dont you do it this way?

$products = ModelsProduct::leftJoin('discounts','discounts.product_id','=','products.id')
  ->leftJoin('categories','categories.id','=','products.category_id')
  ->where('products.status','=','PUBLISHED')
  ->where('discounts.withCode','=','FALSE');
  • Related