Laravel Eloquent ORM 多條件查詢的例子
一、需求:
在數(shù)據(jù)搜索時(shí)最常見的就是調(diào)用同一個(gè)方法查詢,而查詢的字段卻可能是其中一個(gè)或其中的幾個(gè)字段一起組合查詢,例如:對(duì)列表的搜索,基本上都是幾個(gè)字段隨意組合搜索。那么在model里就需要判斷有那個(gè)字段組合,怎么組合。
網(wǎng)上找了很久,Laravel群里也問了幾個(gè),都說沒有寫過,于是自己寫個(gè)吧。話不多說,見代碼:
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);
調(diào)用的時(shí)候,controller里只需要接收這些字段,無論它是否有值,直接加入到$param數(shù)組中查詢就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; }
以上這篇Laravel Eloquent ORM 多條件查詢的例子就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Laravel5.1 框架表單驗(yàn)證操作實(shí)例詳解
這篇文章主要介紹了Laravel5.1 框架表單驗(yàn)證操作,結(jié)合實(shí)例形式詳細(xì)分析了laravel5.1框架表單驗(yàn)證的具體實(shí)現(xiàn)步驟、實(shí)現(xiàn)方法及相關(guān)操作技巧,需要的朋友可以參考下2020-01-01session 加入redis的實(shí)現(xiàn)代碼
本篇文章主要介紹了session 加入redis 的實(shí)例,對(duì)session 進(jìn)行了詳細(xì)介紹,并提供了代碼實(shí)例,需要的朋友可以參考下2016-07-07詳解PHP使用Redis存儲(chǔ)session時(shí)的一個(gè)Warning定位
本篇文章主要介紹了PHP使用Redis存儲(chǔ)session時(shí)的一個(gè)Warning定位,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07laravel7學(xué)習(xí)之無限級(jí)分類的最新實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于laravel7學(xué)習(xí)之無限級(jí)分類的最新實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09php curl模擬post請(qǐng)求小實(shí)例
使用php curl模擬post請(qǐng)求的小例子,提供大家學(xué)習(xí)一下2013-11-11