我需要在 Laravel SQL 查询中添加多个 where 子句。
到目前为止,我的 PHP 代码是:
date_default_timezone_set('America/Los_Angeles');
$today = getdate();
$year = $today['year'];
$month = $today['mon'];
$day = $today['mday'];
$today_ = $day.'-'.$month.'-'.$year;
$result = DB::table('task')
->select('*')
->where(
['rowstate', '<>', 'Ready'],
['DATE_FORMAT(due_date, "%d-%m-%y")', '<', $today_])
->get();
但上面的代码返回:
Column not found: 1054 Unknown column '0' in 'where clause'
(SQL: select * from `task_tab` where (`0` = rowstate and `1` = <> and `2` = Ready))
我想生成下面的SQL语句:
SELET *
FROM task
WHERE rowstate <> 'Ready'
AND DATE_FORMAT(due_date, "%d-%m-%y") < $today
最佳答案
您有 2 种可能的解决方案。
代替:
->where(['rowstate', '<>', 'Ready'], ['DATE_FORMAT(due_date, "%d-%m-%y")', '<', $today_])
你可以使用
->where('rowstate','<>','Ready')->where(DB::raw('DATE_FORMAT(due_date, "%d-%m-%y"','<', $today_);
或
你可以像这样使用数组语法:
->where([
['rowstate', '<>', 'Ready'],
[DB::raw('DATE_FORMAT(due_date, "%d-%m-%y")'), '<', $today_]
]);
总而言之,您缺少将数据封装到外部数组中,如果您不使用原始列名,则需要使用 DB::raw
关于php - Laravel 多个 WHERE 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43693136/