如何允许空白用户输入通过雄辩的Pull()传递?

i34xakig  于 2021-10-10  发布在  Java
关注(0)|答案(2)|浏览(267)

我有一个用户输入文本框,用户可以指定一个特定的过敏原,以避免拉食谱时(由它的id采摘)。例如,如果用户输入“菠萝”,它将在配料表中搜索与“菠萝”匹配的配料,并避免提取与该配料相关的配方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');

然而,问题是用户应该能够将用户文本保留为空白,搜索将继续进行其他方面。当前的问题是,如果用户将文本输入留空,则不会提取任何内容(数组为空)。有没有办法允许空白字段通过?我可以使用if语句检查用户输入是否为空,如果为空,只需删除代码的->wheredoesnthave。但是有没有其他办法解决这个问题呢?

disbfnqx

disbfnqx1#

试试这个

$recipenew = Recipe::where('recipe.suitable_for', $suited);

if ($request->specific_allergen) {
   $recipenew = $recipenew->whereDoesntHave('ingredients', function($QBspecificallergens) use($specificallerg) {
        $QBspecificallergens->where('recipeingredientsmain.ingredientname', 'like', '%specificallerg%');
      });
}

$recipenew = $recipenew->pluck('id);
4nkexdtk

4nkexdtk2#

使用 when ```
$recipenew = Recipe::where('recipe.suitable_for', $suited)
->when(!empty($specificallerg),function ($QBspecificallergens)use($specificallerg){
$QBspecificallergens->whereDoesntHave('ingredients', function($QBspecificallergens) use($specificallerg) {

                $QBspecificallergens->where('recipeingredientsmain.ingredientname', 'like', '%specificallerg%');
            });
        })
        ->pluck('id');
裁判:https://laravel.com/docs/8.x/queries#conditional-第9条:https://laravel.com/docs/8.x/collections#method-什么时候

相关问题