【问题标题】:Laravel execute where condition based on variable null or notLaravel 根据变量是否为 null 执行 where 条件
【发布时间】:2021-05-05 06:52:57
【问题描述】:

我是 laravel 的新手。如果我的变量值不为空,我想执行我的 where 条件。我尝试了下面的代码,完全不知道该怎么做。

$search = $array['search'];
$id = $array['id'];
$Data = Model::where('id', '=', $id)

if($search != '') {
    //I want to include where condition here
}

【问题讨论】:

  • 您希望仅包含基于idsearch 或来自search 的过滤器?

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

使用Conditional Clauses

Model::when($search !== null, function ($query) use ($search) {
    return $query->where('column', $search);
})

【讨论】:

  • $Data = DB::table('mytable')->where('id', '=', $Id) ->when(!is_null($searchBy) !== null,函数 ($query) 使用 ($searchBy) { return $query->where('pid', '=', $searchBy)->orWhere('pname', 'like', '%' . $searchBy . '% ')->orWhere('ps', 'like', '%' . $searchBy . '%'); })->get();根据您的回答,我构建了这个查询,但它没有给我适当的结果。我的查询应该是这样 select * from table where id=$id AND (pid = $searchby OR pname = $searchby OR ps = $searchby)
  • is_null($searchBy) !== null 将始终返回false,因为is_null 返回truefalse。使用when(is_null($search), ...)when($search !== null, ...)。不要合并它们。
  • 知道了。我可以在这样的模型中使用多个条件吗::when($search !== null && $search >0, function ($query) use ($search) { return $query->where('column', $search ); })
  • 只要计算结果为布尔值,您就可以做任何您想做的事情。
【解决方案2】:

您的 $Data 变量是一个 Eloquent Query Builder 对象,因此您可以为正在构建的查询添加条件:

if ($search) {
    $Data->where('field', $search);
}

【讨论】:

    猜你喜欢
    • 2022-10-28
    • 2021-02-17
    • 2022-11-18
    • 1970-01-01
    • 2020-02-18
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    相关资源
    最近更新 更多