このスキーマがあります
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
私はMySQLの作業台でクエリを作成しました
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;
このクエリは実際にこれらのカテゴリすべてを取得します。 product_categories
に存在しないテーブル store_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();
しかし、これでは結果がわかりません
回答:
回答№1は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.*"]);
回答№2の場合は1
あなたは2つの異なるコラムに参加しているので、それを関数/クロージャを通して渡す必要があります。
$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の場所を探しているのであれば、別のクロージャーまたは関数を介してそれを渡すことができます。
回答№3の場合は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