【问题标题】:CakePHP 3 find() with order foreach each rowCakePHP 3 find() 每行的顺序
【发布时间】:2015-08-27 17:45:50
【问题描述】:

伙计,我不知道为什么这不起作用,我正在逐字跟踪 Manuel。

我有一个包含订单列的 ProductStyles 表。假设我有 5 行。然后我删除了第 3 号。我想找到与产品 ID 匹配的所有行,并遍历它们中的每一行,逐步替换订单 #。

Productstyle Table
id - product_id - order

我的第一步是按顺序获取与产品 ID 匹配的所有行,以便我可以执行 foreach,但我不断收到 SQL 错误。老实说,除了基本的选择,我对 SQL 不太了解。

$query = $this->ProductStyles->find()
                ->where(['product_id'=> 1 ])
                ->order(['order' => 'ASC'])
                ;


//debug($query);
//debug( $query->all() ); //this throws an error

错误信息:

错误:SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;查看与您的 MySQL 服务器版本相对应的手册,了解在第 1 行的“order ASC”附近使用的正确语法

SQL:

//SELECT ProductStyles.id AS `ProductStyles__id`, //ProductStyles.product_id AS 
//`ProductStyles__product_id`, ProductStyles.style_id AS //`ProductStyles__style_id`, 
//ProductStyles.order AS `ProductStyles__order` FROM product_styles ProductStyles 
//WHERE product_id = :c0 ORDER BY order ASC
//die;


     $i = 1;
    foreach ($query as $row) {
        //debug($row); die;
        $ps= $this->ProductStyles->get($row->id);
        //debug($ps);die;
        $ps->order = $i;
        $this->ProductStyles->patchEntity($ps,['order'=> $i]);
        $this->ProductStyles->save($ps);
        $i++;
    }

【问题讨论】:

  • 收到错误时,请始终显示准确错误消息,并包括可能的堆栈跟踪和上下文信息!
  • 感谢 NDM 对我的救援 :) 我附上了堆栈跟踪将大量粘贴的错误消息,希望错误消息就足够了

标签: php sql cakephp cakephp-3.0


【解决方案1】:

order 是一个保留字,不允许以不带引号(在本例中为非反引号)的方式使用,它需要以`order` 的形式使用

我建议更改列名,这是最简单且不影响性能的修复。另一种选择是启用自动标识符引用,但这会影响性能,并且不能在任何地方应用,请参阅

Cookbook > Database Access & ORM > Database Basics > Identifier Quoting

【讨论】:

    【解决方案2】:

    order是SQL中的保留关键字,所以,如果你想用作列名,你需要使用引号,像这样:

    SELECT * FROM table ORDER BY `order` ASC
    

    正如您在错误中看到的,没有被引用。

    也许您必须使用$this->Model->query() 并手动编写查询。

    另一种解决方案是将“订单”列更改为另一个名称。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多