简体   繁体   中英

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

My CakePHP 3.0 app uses a MySQL database, which currently has 2 tables with identical structures (but different data). I want to merge these 2 tables, but to keep track of the data, as it has associations.

So, I figured I'd just read in the records from one table, and copy them into the other table with a flag to indicate that they're from the old table, like this:

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

I'm getting the following error:

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

and the SQL query is listed as:

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

It also suggests "Could this be caused by using Auto-Tables?"

Am I doing something silly?

order is a MySQL protected word for use in ordering results. I would either use a different column name or using backticks in your code may work:

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

The SQL error indeed tells you of the problem. In general do not use MySQL protected words in your schema.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM