php - 如何从用户文本输入中搜索数据库记录以查找匹配项并避免提取信息?(PHP)
问题描述
我有两个数据库表,配方表和成分表。一个食谱可以包含许多成分,它们的关系由Recipe_ID 链接。
配方表
- ID
- 适用于
配方成分主表
- ID
- 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%”,而不是输入的值。我怎样才能解决这个问题?
解决方案
您需要从前端获取一个字符串。不是您从表中搜索的那个。
$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');
推荐阅读
- sql - 与 sum() 一起选择列
- c# - 这个 for 循环不止一次地循环遍历相同的值吗?
- c - 定义一个接受多种类型的 API,每种类型都有自己的可能值范围
- php - Laravel LDAP 身份验证不起作用 - LdapRecord 包
- powershell - 如果 Outlook 已在运行,则使用 powershell 在 Outlook 中发送电子邮件而不锁定
- mongodb - 猫鼬在数组列表中按_id查找集合
- c# - 没有表单的操作按钮 | ASP.NET CORE Razor 页面
- javascript - 如何在选项卡式导航中突出显示选定的选项卡
- javascript - 在 javascript/typescript/nodejs 中创建可能的组合
- rotation - 如何在 Red Hat IDM 上自动轮换服务帐户的凭据