Search code examples
phplaravellaravel-5.3

Converting raw queries into laravel


I have this schema

product_categories

id | product_category
---------------------
1  | ABC
2  | DBC
3  | EBA

store_product_categories

id | category_id | store_id
------------------------
1  | 2        | 11
2  | 1        | 11
3  | 3        | 11

I have created a query in mysql work bench

SELECT pc.* FROM product_categories pc LEFT JOIN store_product_categories spc ON pc.category = pc.id AND spc.store_id = 11 WHERE spc.category IS NULL;

This query actually gets all those categories from product_categories table which are not present in store_product_categories.

Now I am really really confused how to build this is Laravel Eloq..

I did try this.

$exclusive_categories = Product_category::join('store_product_categories','store_product_categories.category_id','=','product_categories.id')
        ->where('store_product_categories.store_id','=',session('store_id'))
        ->where('store_product_categories.category_id','=','NULL')->get();

But this doesn't give me result


Solution

  • $exclusive_categories = Product_category::leftJoin('store_product_categories spc', function ($join) {
                $join->on('spc.category_id', '=', 'product_categories.id');
                $join->on('spc.store_id', '=', \DB::raw(session('store_id')));
            })
            ->whereNull('spc.category_id')
            ->get(['product_categories.*']);