Drupal SELECT 查询,SQL 语法中的意外错误

Drupal SELECT query, unexpected error in SQL syntax

在我的自定义模块中,我正在尝试 select 根据 2 个参数、foodType(冰或华夫饼)和限制从我的数据库中订购。

到目前为止,函数和查询如下所示:

public static function getOrders($foodType, $limit){
    $connection = Database::getConnection();
    $query = $connection->select('ice_cream', 'orders');
    $query->condition('orders.foodType', $foodType, '=')
      ->orderBy('id','DESC')
      ->range(0, $limit);
    return $query->execute()->fetchAll();
  }

table的结构是这样的: ice cream table structure

错误报告:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FROM ice_cream ice_cream' at line 1: SELECT FROM {ice_cream} ice_cream; Array ( ) in Drupal\ice_cream\Controller\OrderController::getOrders() (line 57 of C:\xampp\htdocs\imd-theming\site\modules\custom\ice_cream\src\Controller\OrderController.php).

页面错误:

The website encountered an unexpected error. Please try again later.</br></br><em class="placeholder">Drupal\Core\Database\DatabaseExceptionWrapper</em>: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near &#039;FROM
ice_cream orders
WHERE orders.foodType = &#039;ice&#039;
ORDER BY id DESC
LIMIT 5 OFF&#039; at line 1: SELECT 
FROM
{ice_cream} orders
WHERE orders.foodType = :db_condition_placeholder_0
ORDER BY id DESC
LIMIT 5 OFFSET 0; Array
(
    [:db_condition_placeholder_0] =&gt; ice
)
 in <em class="placeholder">Drupal\ice_cream\Controller\OrderController::getOrders()</em> (line <em class="placeholder">54</em> of <em class="placeholder">modules\custom\ice_cream\src\Controller\OrderController.php</em>). <pre class="backtrace">Drupal\Core\Database\Statement-&gt;execute(Array, Array) (Line: 631)
Drupal\Core\Database\Connection-&gt;query(&#039;SELECT 
FROM
{ice_cream} orders
WHERE orders.foodType = :db_condition_placeholder_0
ORDER BY id DESC
LIMIT 5 OFFSET 0&#039;, Array, Array) (Line: 358)
Drupal\Core\Database\Driver\mysql\Connection-&gt;query(&#039;SELECT 
FROM
{ice_cream} orders
WHERE orders.foodType = :db_condition_placeholder_0
ORDER BY id DESC
LIMIT 5 OFFSET 0&#039;, Array, Array) (Line: 510)
Drupal\Core\Database\Query\Select-&gt;execute() (Line: 54)
Drupal\ice_cream\Controller\OrderController::getOrders(&#039;ice&#039;, &#039;5&#039;) (Line: 88)
... (Omitted the rest since it's not SQL related anymore.)

我认为您需要告诉它要拉回哪些字段。例如,如果你想提取每条记录的 ID,你可以这样做:

$query->fields('orders', ['id']);