【问题标题】:How to search database records for a match from user text input and avoid pulling the information? (PHP)如何从用户文本输入中搜索数据库记录以查找匹配项并避免提取信息? (PHP)
【发布时间】:2021-10-02 05:47:28
【问题描述】:

我有两个数据库表,配方表和配​​料表。一个食谱可以包含许多成分,它们的关系由 Recipe_ID 链接。

食谱表

  • 身份证
  • 适合

RecipeIngredients 主表

  • 身份证
  • recipe_id
  • 成分名称

我有一个用户输入表单,用户可以在其中决定向他们推荐哪些食谱的限制条件。我有一个文本框输入,允许用户输入“特定过敏”。提取的这个值将在成分表中搜索名称匹配,如果通过查询关系缺失找到匹配项,则避免提取 Recipe_ID。

例如,如果用户输入“菠萝”,如果在成分表中找到匹配项,则会避免拉取Recipe_ID。

Recipe 在模型中有很多关系:

public function ingredients()
{
return $this->hasMany(Ingredients::class, 'recipe_id');
}

拉取用户输入:

$suited = $request->suitable_for;
$specificallerg = $request->specific_allergen;

Controller中的代码:

$recipenew = Recipe::where('recipe.suitable_for', $suited)
    ->whereDoesntHave('ingredients', function($QBspecificallergens) use($specificallerg) {
        $QBspecificallergens->where('recipeingredientsmain.ingredientname', 'like', '%specificallerg%');
      })->pluck('id');

代码运行,但我的问题是逻辑错误,因为它在“成分名称”中搜索字面意思是“%specificallerg%”,而不是输入的值。我该如何解决这个问题?

【问题讨论】:

  • ('recipeingredientsmain.ingredientname', 'like', '%'.$specificallerg.'%'); 你传递的是字符串而不是变量。
  • 就我个人而言,我会为配料制作一张不同的桌子,因为您可能希望其他食谱使用相同的配料。

标签: php database laravel eloquent relationship


【解决方案1】:

您需要从前端获取您正在请求的字符串。不是您要从表中搜索的那个。

$suited = $request->suitable_for;
$specificallerg = $request->specific_allergen;


$recipenew = Recipe::where('recipe.suitable_for', $suited)
    ->whereDoesntHave('ingredients', function($QBspecificallergens) use($specificallerg) {
        $QBspecificallergens->where('recipeingredientsmain.ingredientname', 'like', '%'.$specificallerg.'%');
      })->pluck('id');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多