Laravel中where高级用法如何结合多个条件实现复杂查询?

2026-04-06 07:071阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计294个文字,预计阅读时间需要2分钟。

Laravel中where高级用法如何结合多个条件实现复杂查询?

在项目中有时候需要执行多个字段搜索,可以使用此方法。在Laravel中,可同时使用多个where,我们可以为每个字段分配一个where()。然后在每个where()中进行包裹判断。例如:

Laravel中where高级用法如何结合多个条件实现复杂查询?

php$users=User::where('username', 'LIKE', '%' . $username . '%') ->where('name', 'LIKE', '%' . $username . '%') ->get();

有时候项目中需要进行多个字段搜索就可以用到此方法

  • 在Laravel中的可以同时使用多个where,所以我们可以每个字段分配一个where()
  • 然后在每个where()中去闭包判断

$username = '';// 收货人姓名 $hospital_id = ''; // 医院id # 判断是否有姓名搜索 if (!empty($request->username)) { $username = $request->username; } # 判断是否有医院搜索 if (!empty($request->hospital_id)) { $hospital_id = $request->hospital_id; } # 执行 $data = DB::table('test') ->where(function($query)use($username){ # 进行判断 if (!empty($username)) { $query->where('username','Like',"%$username%"); } }) ->where(function($query)use($hospital_id){ # 进行判断 if (!empty($hospital_id)) { $query->where('hospital_id','=',$hospital_id); } }) ->get() ->toArray(); dd($data)

到此这篇关于Laravel中的where高级使用方法实例讲解的文章就介绍到这了,更多相关Laravel中的where高级使用方法内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!

本文共计294个文字,预计阅读时间需要2分钟。

Laravel中where高级用法如何结合多个条件实现复杂查询?

在项目中有时候需要执行多个字段搜索,可以使用此方法。在Laravel中,可同时使用多个where,我们可以为每个字段分配一个where()。然后在每个where()中进行包裹判断。例如:

Laravel中where高级用法如何结合多个条件实现复杂查询?

php$users=User::where('username', 'LIKE', '%' . $username . '%') ->where('name', 'LIKE', '%' . $username . '%') ->get();

有时候项目中需要进行多个字段搜索就可以用到此方法

  • 在Laravel中的可以同时使用多个where,所以我们可以每个字段分配一个where()
  • 然后在每个where()中去闭包判断

$username = '';// 收货人姓名 $hospital_id = ''; // 医院id # 判断是否有姓名搜索 if (!empty($request->username)) { $username = $request->username; } # 判断是否有医院搜索 if (!empty($request->hospital_id)) { $hospital_id = $request->hospital_id; } # 执行 $data = DB::table('test') ->where(function($query)use($username){ # 进行判断 if (!empty($username)) { $query->where('username','Like',"%$username%"); } }) ->where(function($query)use($hospital_id){ # 进行判断 if (!empty($hospital_id)) { $query->where('hospital_id','=',$hospital_id); } }) ->get() ->toArray(); dd($data)

到此这篇关于Laravel中的where高级使用方法实例讲解的文章就介绍到这了,更多相关Laravel中的where高级使用方法内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!