如何使用CakePHP 3.0将新记录插入数据库?

时间:2018-03-14 18:35:42

标签: mysql cakephp cakephp-3.0

我的CakePHP 3.0应用程序使用MySQL数据库,该数据库目前有2个表具有相同的结构(但数据不同)。我想合并这两个表,但要跟踪数据,因为它有关联。

所以,我想我只是从一个表中读取记录,并将它们复制到另一个表中,并带有一个标志,表明它们来自旧表,如下所示:

public function copyarchive() {
    $oldalbums= TableRegistry::get('Archivealbums');
    $newalbums= TableRegistry::get('Albums');
    $albumlist = $oldalbums->find(); // Get all archived albums
    foreach($albumlist as $oldalbum) {
        // Copy album details to album table and get new id
        $newalbum = $newalbums->newEntity([
                    'is_archive' => 1,
                    'name' => $oldalbum->name,
                    'date' => $oldalbum->date,
                    'description' => $oldalbum->description,
                    'order' => $oldalbum->order,
        ]);
        if ($newalbums->save($newalbum)) {
            $id = $newalbum->id;
            // ... now do other things ...
        }
     }
 }

我收到以下错误:

Error: 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 'order) VALUES (1, 'Pre-1920\'s', '2013-10-22 23:00:00', '<p>\r\n  Photos from bef' at line 1

,SQL查询列为:

INSERT INTO albums (is_archive, name, date, description, order) VALUES (:c0, :c1, :c2, :c3, :c4)

它还暗示“这可能是由使用自动表引起的吗?”

我在做些傻事吗?

1 个答案:

答案 0 :(得分:2)

order 是一个MySQL保护字,用于排序结果。我要么使用不同的列名,要么在代码中使用反引号可能有效:

public function copyarchive() {
    $oldalbums= TableRegistry::get('Archivealbums');
    $newalbums= TableRegistry::get('Albums');
    $albumlist = $oldalbums->find(); // Get all archived albums
    foreach($albumlist as $oldalbum) {
        // Copy album details to album table and get new id
        $newalbum = $newalbums->newEntity([
                    'is_archive' => 1,
                    'name' => $oldalbum->name,
                    'date' => $oldalbum->date,
                    'description' => $oldalbum->description,
                    '`order`' => $oldalbum->order,
        ]);
        if ($newalbums->save($newalbum)) {
            $id = $newalbum->id;
            // ... now do other things ...
        }
     }
 }

SQL错误确实告诉您问题所在。通常,不要在架构中使用受MySQL保护的单词。