2017-01-30 10 views
0

に生のクエリを変換する私はMySQLの作業台でクエリを作成しているlaravel

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 

このスキーマを持って

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;

store_product_categoriesに存在しないproduct_categoriesテーブルからこれらのカテゴリを実際にすべて取得します。

今、私はこれを構築する方法を本当に混乱していますがLaravel Eloq ..です

私はこれを試してみました。

$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(); 

しかし、これは私が使用すると、2つの異なる列に参加しているので、あなたが機能/クロージャを通じてそれを渡す必要が

答えて

0
$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.*']); 
0
$exclusive_categories = Product_category::leftJoin('store_product_categories','store_product_categories.category_id','=','product_categories.id') 
     ->where('store_product_categories.store_id','=',session('store_id')) 
     ->whereNull('store_product_categories.store_id')->get(); 

https://laravel.com/docs/5.3/queries

+0

動作しません!クエリを徹底的にチェックしてください!私の質問 – Alex

+0

あなたの質問を実行しようとしましたか? 返されたデータは何ですか? $ exclusive_categories = PRODUCT_CATEGORY :: leftJoin( 'store_product_categories'、 'store_product_categories.category_id'、 '='、 'product_categories.id') - >( 'store_product_categories.store_id'、 '='、セッション( 'STORE_ID '))) - > whereNull(' store_product_categories.category_id ') - > get(); –

1

つながるものではありません。

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

これがあなたの望むものであるかどうかはわかりません。 store_idがNULLの場所を探している場合やstore_id =セッションIDの場合は、別のクロージャ/関数を渡すことができます。

+0

この奇妙なエラーが発生しました – Alex

+0

カラムが見つかりません:1054不明なカラム 'on clause'(SQL:select * from 'product_categories'はstore_product_categories'.category_id' = 'product_categories'にstore_product_categories'を残します。 'store_product_categories'。' category_id' = NULL) – Alex

+0

私の答えを確認してください。 –