Laravel Eloquent ORM 一种高级用法

        一、需求:

在数据搜索时最常见的就是调用同一个方法查询,而查询的字段却可能是其中一个或其中的几个字段一起组合查询,例如:对列表的搜索,基本上都是几个字段随意组合搜索。那么在model里就需要判断有那个字段组合,怎么组合。
       网上找了很久,Laravel群里也问了几个,都说没有写过,于是自己写个吧。话不多说,见代码:
        
function findByParam($param = array())
  {
    $select = new Customer();
    if (isset($param['name']) && '' != $param['name'])
    {
      $select = $select->where('customer.name', '=', $param['name']);
    }
    if (isset($param['phone']) && '' != $param['phone'])
    {
      $select = $select->where('customer.phone', '=', $param['phone']);
    }
    if (isset($param['email']) && '' != $param['email'])
    {
      $select = $select->where('customer.email', '=', $param['email']);
    }
    if (isset($param['tel']) && '' != $param['tel'])
    {
      $select = $select->where('customer.tel', '=', $param['tel']);
    }
    if (isset($param['qq']) && '' != $param['qq'])
    {
      $select = $select->where('customer.qq', '=', $param['qq']);
    }
    if (isset($param['IDCard']) && '' != $param['IDCard'])
    {
      $select = $select->where('customer.IDCard', '=', $param['IDCard']);
    }
    
    $customers = $select->leftJoin("member", function ($join)
    {
      $join->on("customer.memberID", "=", "member.id");
    })
      ->get(array(
      'customer.id',
      'customer.name',
      'customer.sex',
      'customer.tel',
      'customer.phone',
      'customer.address',
      'customer.email',
      'customer.qq',
      'customer.headPic',
      'customer.birthday',
      'customer.IDCard',
      'customer.enable',
      'customer.memberID',
      'customer.IDCard',
      'customer.info',
      'member.name as mname',
      'member.discount'
    ));
    return json_encode($customers);
        调用的时候,controller里只需要接收这些字段,无论它是否有值,直接加入到$param数组中查询就OK,例如:
      
function anyFindbyparam()
  {
    $name = Input::get('name');
    $tel = Input::get('tel');
    $phone = Input::get('phone');
    $email = Input::get('email');
    $qq = Input::get('qq');
    $IDCard = Input::get('IDCard');
    $customer = new Customer();
    $customers = $customer->findByParam(array(
      'name' => $name,
      'tel' => $tel,
      'phone' => $phone,
      'email' => $email,
      'qq' => $qq,
      'IDCard' => $IDCard
    ));
    return $customers;
  }
    尊重原创,转载请注明出处:http://blog.csdn.net/a437629292/article/details/44038411
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜鸟没翅膀

你的打赏是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值