Laravel 多个 WHERE 子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43693136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:52:59  来源:igfitidea点击:

Laravel multiple WHERE clauses

phplaravellaravel-5eloquentlaravel-5.4

提问by Lakmal Premaratne

I have a requirement to add multiple where clauses to a Laravel SQL query.

我需要向 Laravel SQL 查询添加多个 where 子句。

So far my PHP code has been:

到目前为止,我的 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();

But above code returns:

但上面的代码返回:

Column not found: 1054 Unknown column '0' in 'where clause' 
(SQL: select * from `task_tab` where (`0` = rowstate and `1` = <> and `2` = Ready))

I want to generate below SQl statement:

我想生成以下 SQl 语句:

SELET * 
FROM task
WHERE rowstate <> 'Ready'
AND DATE_FORMAT(due_date, "%d-%m-%y") < $today

回答by Marcin Nabia?ek

You have 2 possible solutions.

您有 2 种可能的解决方案。

Instead of:

代替:

->where(['rowstate', '<>', 'Ready'], ['DATE_FORMAT(due_date, "%d-%m-%y")', '<', $today_])

you can use

您可以使用

->where('rowstate','<>','Ready')->where(DB::raw('DATE_FORMAT(due_date, "%d-%m-%y"','<', $today_);

or

或者

you can use array syntax like this:

您可以使用这样的数组语法:

->where([
    ['rowstate', '<>', 'Ready'], 
    [DB::raw('DATE_FORMAT(due_date, "%d-%m-%y")'), '<', $today_]
 ]);

So to sum up you were missing enclosing your data into outer array, and you need to use DB::rawin case you don't use raw column names

总而言之,您缺少将数据包含在外部数组中,DB::raw如果不使用原始列名,则需要使用

回答by Pankit Gami

You can't use sql function's directly in laravel where class. You need to use DB::raw()for same.

你不能直接在 laravel where 类中使用 sql 函数。你需要使用DB::raw()相同的。

So your query will be like :

所以你的查询将是这样的:

$result = DB::table('task')
    ->select('*')
    ->where('rowstate', '<>', 'Ready')
    ->where(DB::raw('DATE_FORMAT(due_date, "%d-%m-%y")'), '<', $today_)
    ->get();

回答by Joe Black

Try this

尝试这个

->where([
//      ^
    ['rowstate', '<>', 'Ready'],
    ['DATE_FORMAT(due_date, "%d-%m-%y")', '<', $today_]])
//                                                     ^