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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (43)

我的CakePHP 3.0应用程序使用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 ...
        }
     }
 }

我收到以下错误:

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)
提问于
用户回答回答于

代码:

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 ...
        }
     }
 }

扫码关注云+社区

领取腾讯云代金券