首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有一个“连接”和“在哪里”的Laravel查询,以获得一个基于过敏原限制的食谱?

有一个“连接”和“在哪里”的Laravel查询,以获得一个基于过敏原限制的食谱?
EN

Stack Overflow用户
提问于 2021-07-23 11:59:13
回答 1查看 37关注 0票数 0

我正在试验Laravel8.0x口才和查询生成器,以便生成一个包含由用户输入约束选择的菜谱的膳食计划。例如,用户输入他们正在寻找的晚餐 (meal_type)、Vegetarian (suitable_for)、6 people (Feed)、2天的膳食计划(days)。然后根据这些约束从数据库中提取菜谱ID。输入表单都是下拉的,除了过敏原是一个复选框(因为用户可能有多个过敏原)。

当谈到过敏原,一个食谱可以有多种过敏原。有两个表,食谱和Recipe_Allergens。Recipe_Allergens有id、Recipe_ID和Allergen_Description字段。复选框请求需要内爆:

代码语言:javascript
复制
$request->merge([ 'allergens' => implode(',', (array) $request->get('allergens')) ]);

因此,如果检查两个过敏原,‘乳酪’和‘面筋’,结果被保存为‘乳酪,面筋’。然而,我希望它循环通过每一个单独的过敏原,以检查食谱是否包含任何这些过敏原,并避免选择该Recipe_ID,如果它有。

用户输入:

代码语言:javascript
复制
$meal = $request->meal_type;
$suited = $request->suitable_for;
$allerg = $request->allergens;
$feeds = $request->no_of_people;
$days = $request->no_of_days;

$allergenarray2 = explode(",", $allerg); 

通过菜谱id和“where”,雄辩的“连接”(Join),以获得Recipe_ID:

代码语言:javascript
复制
$recipenew = Recipe::join('recipe_allergens', 'recipe_allergens.recipe_id', '=', 'recipe.id')->where('recipe.suitable_for', $suited)->where('recipe_allergens.allergen_description', '!=', $allergenarray2)->where('recipe.feeds_total', $feeds)->get();

输入DB表:

代码语言:javascript
复制
while ($x < $days){
  $recidnew =  $recipenew[$x]->id;
MealPlanDisplay::create([
      'Recipe_ID' => $recipenew[$x],
      'Day' =>  $recipeday,
      'user_id' => $currentuserid,
]);
$x = $x + 1;
}

除了过敏原外,所有的约束都有效。这类加入有用吗?它似乎也不会接受爆炸的数组,只会识别其中的第一个值(例如,乳酪,面筋只被认为是‘乳酪’)。我能做什么?

EN

回答 1

Stack Overflow用户

发布于 2021-07-23 12:15:35

使用whereNotIn()函数代替where条件,并在参数中传递数组和列名,如

代码语言:javascript
复制
$recipenew = Recipe::join('recipe_allergens', 'recipe_allergens.recipe_id', '=', 'recipe.id')->where('recipe.suitable_for', $suited)->whereNotIn('recipe_allergens.allergen_description', $allergenarray2)->where('recipe.feeds_total', $feeds)->get();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68498826

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档