Drupal 7 - db_select: SQL 函数在 where 条件下
Drupal 7 - db_select: SQL function in where condition
我需要在我的 select 语句中使用这个条件:
WHERE YEAR(date) = YEAR(CURDATE())
但如果我这样做,就像这样:
$query = db_select('table', 't');
$query->fields('t');
$query->condition('YEAR\(date\)', 'YEAR(CURDATE())', '=');
Drupal 不会有它(即使我没有转义那些括号 - 它只是忽略它们)因为我得到一个错误:
Column not found: 1054 Unknown column 'YEARdate' in 'where clause':
如何克服这个错误?
嗯.. 就这样,好像:
$query->where('YEAR(date) = YEAR(CURDATE())');
where
允许任意 SQL:
The where() method allows for the addition of arbitrary SQL as a conditional fragment. $snippet may contain any legal SQL fragment, and if it has variable content it must be added using a named placeholder. The $args array is an array of placeholders and values that will be substituted into the snippet. It is up to the developer to ensure that the snippet is valid SQL. No database-specific modifications are made to the snippet.
嗯,你也可以使用 db_query,它允许你编写 SQL 查询 "without Drupal"。
我的意思是,您将能够添加自定义 WHERE 语句或任何 SQL-适当的函数,例如自定义函数 ;)
例如
$result = db_query('SELECT title FROM {node} WHERE type = "%s" AND title LIKE "%%%s%%"', 'type', 'title');
使用addExpression
方法:
https://api.drupal.org/api/drupal/includes!database!select.inc/function/SelectQuery%3A%3AaddExpression/7.x
$query = db_select('table', 't');
$query->fields('t');
$query->addExpression('YEAR(t.date) = YEAR(CURDATE())');
$result = $query->execute()->fetchAll();
var_dump($result);
我需要在我的 select 语句中使用这个条件:
WHERE YEAR(date) = YEAR(CURDATE())
但如果我这样做,就像这样:
$query = db_select('table', 't');
$query->fields('t');
$query->condition('YEAR\(date\)', 'YEAR(CURDATE())', '=');
Drupal 不会有它(即使我没有转义那些括号 - 它只是忽略它们)因为我得到一个错误:
Column not found: 1054 Unknown column 'YEARdate' in 'where clause':
如何克服这个错误?
嗯.. 就这样,好像:
$query->where('YEAR(date) = YEAR(CURDATE())');
where
允许任意 SQL:
The where() method allows for the addition of arbitrary SQL as a conditional fragment. $snippet may contain any legal SQL fragment, and if it has variable content it must be added using a named placeholder. The $args array is an array of placeholders and values that will be substituted into the snippet. It is up to the developer to ensure that the snippet is valid SQL. No database-specific modifications are made to the snippet.
嗯,你也可以使用 db_query,它允许你编写 SQL 查询 "without Drupal"。 我的意思是,您将能够添加自定义 WHERE 语句或任何 SQL-适当的函数,例如自定义函数 ;)
例如
$result = db_query('SELECT title FROM {node} WHERE type = "%s" AND title LIKE "%%%s%%"', 'type', 'title');
使用addExpression
方法:
https://api.drupal.org/api/drupal/includes!database!select.inc/function/SelectQuery%3A%3AaddExpression/7.x
$query = db_select('table', 't');
$query->fields('t');
$query->addExpression('YEAR(t.date) = YEAR(CURDATE())');
$result = $query->execute()->fetchAll();
var_dump($result);