php - Laravel:语法错误或访问冲突导致我也像字段一样使用 'order'

标签 php mysql sql laravel

当 Laravel 执行一个查询时,我收到此错误。

功能是这样的:

public function updateOrder(Request $request)
   {

       $queryParams = [];

       $ids = $request->ids;


       //el query será definido en su totalidad de forma manual
       $query = 'UPDATE projects SET order = CASE id ';

       //agregamos cada parámetro de orden y de id al array para respetar las convenciones de PDO
       foreach ($ids as $order => $id) {
           $query .= 'WHEN ? THEN ? ';
           $queryParams[] = (int) $id;
           $queryParams[] = (int) $order;
       }

       //por último agregamos los ids implicados en el update
       $queryParams = array_merge($queryParams, $ids);

       //generamos los ? necesarios para el array de ids en el query PDO
       $whereInArray = array_fill(0, count($ids), '?');
       $whereInString = implode(", ", $whereInArray);

       //agregamos dicho string generado al query final
       $query .= "END WHERE id IN ($whereInString)";

       //realizamos el update
       DB::update($query, $queryParams);
   }     

我想我知道问题出在哪里,我的字段称为 order,我认为 order 它是 Laravel 保留的。

我的所有应用程序都使用“订单”字段。

我尝试将其更改为“排序”,并且它有效,但我无法更改所有项目。

我该如何使用订单?

错误如下所示:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an 
error in your SQL syntax; check the manual that corresponds to your     
MySQL server version for the right syntax to use near ''projects' SET 
'order' = CASE 'id' WHEN ? THEN ? WHEN ? THEN ? WHEN ? THEN ? WHE' at 
line 1 (SQL: UPDATE 'projects' SET 'order' = CASE 'id' WHEN 25 THEN 0 
WHEN 23 THEN 1 WHEN 26 THEN 2 WHEN 19 THEN 3 WHEN 27 THEN 4 WHEN 18 
THEN 5 WHEN 28 THEN 6 WHEN 14 THEN 7 WHEN 24 THEN 8 WHEN 20 THEN 9 
WHEN 12 THEN 10 WHEN 13 THEN 11 WHEN 17 THEN 12 WHEN 29 THEN 13 WHEN 
15 THEN 14 WHEN 21 THEN 15 WHEN 16 THEN 16 WHEN 22 THEN 17 WHEN 4 
THEN 18 WHEN 3 THEN 19 WHEN 1 THEN 20 WHEN 6 THEN 21 WHEN 9 THEN 22 
WHEN 8 THEN 23 WHEN 5 THEN 24 WHEN 2 THEN 25 WHEN 10 THEN 26 WHEN 11 
THEN 27 WHEN 7 THEN 28 END WHERE id IN (25, 23, 26, 19, 27, 18, 28, 
14, 24, 20, 12, 13, 17, 29, 15, 21, 16, 22, 4, 3, 1, 6, 9, 8, 5, 2, 
10, 11, 7))

最佳答案

如果您使用reserved word in MySQL,可能会发生此错误,例如 fromorder 作为列名称,而不使用反引号。在您的情况下,问题出在单词 order 上。所以改变:

$query = 'UPDATE projects SET order = CASE id ';

至:

$query = 'UPDATE `projects` SET `order` = CASE `id` ';

它应该可以工作。反引号转义列名称。此类名称称为“带引号的标识符”。

一些程序员不喜欢使用反引号,因此他们使用明显避免保留字集的列名。

关于php - Laravel:语法错误或访问冲突导致我也像字段一样使用 'order',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45956094/

相关文章:

javascript - 从 ajax 返回值并将该值设置为变量

mysql - 错误exec.DDLTask:java.lang.NoSuchMethod错误:

python - pip install MySql-python==1.2.4 在 Ubuntu 12.04 上失败

php - 在 PHP 中模拟 LIKE

MySQL - 在哪里或?

php - MySQL - 将数据附加到现有字段/记录的建议?

php - MySQL 日期时间与 session 中设置的日期时间。哪一个先出现?

php - 在多列中显示数据

python - 通过 python 来自 mariadb 的错误文本

mysql - 根据其他表值选择 GROUP BY 的 ID