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

How do I insert a new record into the database with CakePHP 3.0?

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

所以,我想我只是从一个 table 中读取记录,然后将它们复制到另一个 table 中,并用一个标志来表明它们来自旧的 table,像这样:

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)

还建议"Could this be caused by using Auto-Tables?"

我是不是在做傻事?

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 受保护的词。