1. 程式人生 > >laravel5.3-數據庫操作下的局部or條件與全局or條件(orWhere的局部與全局)

laravel5.3-數據庫操作下的局部or條件與全局or條件(orWhere的局部與全局)

bsp trim con pty 數據庫 區別 替換 derby 是我

當用戶名不為空時

SELECT * FROM `ACCOUNT_RECHARGE` LEFT JOIN `ORDER` ON `ACCOUNT_RECHARGE`.`OrderNo` = `ORDER`.`OrderNo` LEFT JOIN `USER_ACCOUNT` ON `ORDER`.`UserId` = `USER_ACCOUNT`.`UserId` WHERE (`USER_ACCOUNT`.`UserName` LIKE ‘%18%‘ OR (`USER_ACCOUNT`.`MobileNo` LIKE ‘%18%‘) OR (`USER_ACCOUNT`.`EMail` LIKE ‘%18%‘))

AND `ACCOUNT_RECHARGE`.`OrderTime` BETWEEN ‘2017-08-11 0:0:0‘ AND ‘2017-08-11 23:59:59‘ ORDER BY `ACCOUNT_RECHARGE`.`OrderTime` DESC;

上述SQL語句在laravel5.3中的一種寫法:

$model = DB::connection(‘Order_User‘)->table(‘ACCOUNT_RECHARGE‘)

                 ->leftJoin(‘ORDER‘, ‘ACCOUNT_RECHARGE.OrderNo‘, ‘=‘, ‘ORDER.OrderNo‘)

                 ->leftJoin(‘USER_ACCOUNT‘, ‘ORDER.UserId‘, ‘=‘, ‘USER_ACCOUNT.UserId‘)
                 
->select(‘ACCOUNT_RECHARGE.*‘, ‘USER_ACCOUNT.UserName‘, ‘USER_ACCOUNT.MobileNo‘, ‘USER_ACCOUNT.EMail‘)

                 ->orderBy(‘ACCOUNT_RECHARGE.OrderTime‘, ‘DESC‘);
if (!empty($username)) {
$username = trim($username);
$model = $model->where(function($query) use ($username) {
  $query->where(‘USER_ACCOUNT.UserName‘, ‘like‘, "%$username%")
     ->orWhere(function($query) use ($username) {
        $query->where(‘USER_ACCOUNT.MobileNo‘, ‘like‘, "%$username%");
      });
     ->orWhere(function($query) use ($username) {
        $query->where(‘USER_ACCOUNT.EMail‘, ‘like‘, "%$username%");
      });
  });
}

註意:在username不為空的判斷裏面,若沒有使用use則會報未定義的變量username

對比

第一種

$model = $model->where(function($query) use ($username) {
  $query->where(‘USER_ACCOUNT.UserName‘, ‘like‘, "%$username%")
     ->orWhere(function($query) use ($username) {
        $query->where(‘USER_ACCOUNT.MobileNo‘, ‘like‘, "%$username%");
      });
     ->orWhere(function($query) use ($username) {
        $query->where(‘USER_ACCOUNT.EMail‘, ‘like‘, "%$username%");
      });
  });
}

第二種

$model = $model >where(‘USER_ACCOUNT.UserName‘, ‘like‘, "%$username%")->orWhere(‘MobileNo‘, ‘like‘, "%$username%")->orWhere
(‘EMail‘, ‘like‘, "%$username%");
}

的區別

第一種是局部的or條件,只是對username的or判斷,而與其它條件是並且的關系,對照剛開始出現的SQL語句

而第二種是全局的or條件,若把第二種的語句替換掉第一種的語句,相當於SQL語句

SELECT * FROM `ACCOUNT_RECHARGE` LEFT JOIN `ORDER` ON `ACCOUNT_RECHARGE`.`OrderNo` = `ORDER`.`OrderNo` LEFT JOIN `USER_ACCOUNT` ON `ORDER`.`UserId` = `USER_ACCOUNT`.`UserId` WHERE `USER_ACCOUNT`.`UserName` LIKE ‘%18%‘ OR (`USER_ACCOUNT`.`MobileNo` LIKE ‘%18%‘) OR (`USER_ACCOUNT`.`EMail` LIKE ‘%18%‘) AND `ACCOUNT_RECHARGE`.`OrderTime` BETWEEN ‘2017-08-11 0:0:0‘ AND ‘2017-08-11 23:59:59‘ ORDER BY `ACCOUNT_RECHARGE`.`OrderTime` DESC;

這時,你會發現,只要username存在,你的其它條件就會失效。

這是我跳過的坑......

laravel5.3-數據庫操作下的局部or條件與全局or條件(orWhere的局部與全局)