经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » PHP » 查看文章
Laravel Eloquent ORM 多条件查询的例子
来源:jb51  时间:2019/10/10 11:07:52  对本文有异议

一、需求:

在数据搜索时最常见的就是调用同一个方法查询,而查询的字段却可能是其中一个或其中的几个字段一起组合查询,例如:对列表的搜索,基本上都是几个字段随意组合搜索。那么在model里就需要判断有那个字段组合,怎么组合。

网上找了很久,Laravel群里也问了几个,都说没有写过,于是自己写个吧。话不多说,见代码:

  1. function findByParam($param = array())
  2. {
  3. $select = new Customer();
  4. if (isset($param['name']) && '' != $param['name'])
  5. {
  6. $select = $select->where('customer.name', '=', $param['name']);
  7. }
  8. if (isset($param['phone']) && '' != $param['phone'])
  9. {
  10. $select = $select->where('customer.phone', '=', $param['phone']);
  11. }
  12. if (isset($param['email']) && '' != $param['email'])
  13. {
  14. $select = $select->where('customer.email', '=', $param['email']);
  15. }
  16. if (isset($param['tel']) && '' != $param['tel'])
  17. {
  18. $select = $select->where('customer.tel', '=', $param['tel']);
  19. }
  20. if (isset($param['qq']) && '' != $param['qq'])
  21. {
  22. $select = $select->where('customer.qq', '=', $param['qq']);
  23. }
  24. if (isset($param['IDCard']) && '' != $param['IDCard'])
  25. {
  26. $select = $select->where('customer.IDCard', '=', $param['IDCard']);
  27. }
  28. $customers = $select->leftJoin("member", function ($join)
  29. {
  30. $join->on("customer.memberID", "=", "member.id");
  31. })
  32. ->get(array(
  33. 'customer.id',
  34. 'customer.name',
  35. 'customer.sex',
  36. 'customer.tel',
  37. 'customer.phone',
  38. 'customer.address',
  39. 'customer.email',
  40. 'customer.qq',
  41. 'customer.headPic',
  42. 'customer.birthday',
  43. 'customer.IDCard',
  44. 'customer.enable',
  45. 'customer.memberID',
  46. 'customer.IDCard',
  47. 'customer.info',
  48. 'member.name as mname',
  49. 'member.discount'
  50. ));
  51. return json_encode($customers);

调用的时候,controller里只需要接收这些字段,无论它是否有值,直接加入到$param数组中查询就OK,例如:

  1. function anyFindbyparam()
  2. {
  3. $name = Input::get('name');
  4. $tel = Input::get('tel');
  5. $phone = Input::get('phone');
  6. $email = Input::get('email');
  7. $qq = Input::get('qq');
  8. $IDCard = Input::get('IDCard');
  9. $customer = new Customer();
  10. $customers = $customer->findByParam(array(
  11. 'name' => $name,
  12. 'tel' => $tel,
  13. 'phone' => $phone,
  14. 'email' => $email,
  15. 'qq' => $qq,
  16. 'IDCard' => $IDCard
  17. ));
  18. return $customers;
  19. }

以上这篇Laravel Eloquent ORM 多条件查询的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号