首页 > 解决方案 > 如何从用户文本输入中搜索数据库记录以查找匹配项并避免提取信息?(PHP)

问题描述

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

配方表

配方成分主表

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

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

模型中的配方有很多关系:

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

拉取用户输入:

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

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

标签: phpdatabaselaraveleloquentrelationship

解决方案


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

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

推荐阅读