我有以下表格:
餐具
id
name
客户
id
name
成分
id
name
Dishes_Ingredients (关于菜肴和食材的表格)
id
dish_id
ingredient_id
Customers_Allergic_Ingredients (客户对某些成分过敏)
id
customer_id
ingredient_id
Customers_Intolerance_Ingredients (客户不能容忍某些成分)
id
customer_id
ingredient_id
我需要从数据库中获取以下信息:对于给定的customer_id
,我想要检索客户不过敏且不耐受的所有菜肴,使用Laravel查询生成器。
这是我到目前为止所尝试的:
$dishes = DB::table('dishes')
->join('dishes_ingredients', 'dishes.id', '=', 'dishes_ingredients.dish_id')
->join('customers_allergic_ingredients', 'dishes_ingredients.ingredient_id', '<>', 'customers_allergic_ingredients.ingredient_id')
->join('customers_intolerance_ingredients', 'dishes_ingredients.ingredient_id', '<>', 'customers_intolerance_ingredients.ingredient_id')
->where('customers.id', 1)
->select('dishes.id', 'dish_translations.name')
->get();
答案 0 :(得分:0)
我不知道Laravel,但如果你只想解决问题:
SELECT *
FROM Dishes d
WHERE d.id NOT IN
(
SELECT DISTINCT dish_id
FROM Dishes_Ingridients
WHERE ingredient_id IN
(SELECT DISTINCT ingredient_id FROM Customers_Allergic_Ingredients cai WHERE cai.customer_id = ?)
OR
ingredient_id IN
(SELECT DISTINCT ingredient_id FROM Customers_Intolerance_Ingredients cii WHERE cii.customer_id = ?)
)
答案 1 :(得分:0)
尝试使用 Laravel Eloquent:Relationships
这将节省您的时间和时间。你的代码会更简单......答案 2 :(得分:0)
$dishes = DB::table("dishes AS a")
->select(array("a.*" ))
->join("dishes_ingredients AS b", "a.id", "b.dish_id")
->join("Customers_Allergic_Ingredients AS c", "b.id", "=", "c.ingredient_id")
->where("c.customer_id", "!=", $customer_id)
->groupBy("a.id")
->get();
这将为您提供所有使用客户不会过敏的成分制作的菜肴