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 数组中传递给查询方法即可。具体调用方式如下:
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;
}
以上即为 Laravel Eloquent ORM 处理多条件组合查询的完整示例,旨在为开发者提供参考思路,欢迎支持本站更多内容。