Skip to content
Advertisement

Laravel Join If Column Value Not Null

$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

Advertisement

Answer

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');
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement