如何在查询生成器中使用insert插入多个记录?

时间:2014-10-27 16:03:31

标签: mysql cakephp cakephp-3.0

我在CakePHP 3中尝试以下内容:

   $newUsers = [
        [
            'username' => 'Felicia',
            'age' => 27,
        ],
        [
            'username' => 'Timmy',
            'age' => 71,
        ],
    ];

    $insertQuery = $this->Users->query();

    $insertQuery->insert(array_keys($newUsers[0]))
                ->values($newUsers)
                ->execute();

我收到以下错误:

Error: SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1

SQL Query: INSERT INTO users (username, age) VALUES (:c0, :c1, :c2, :c3) 

我期待INSERT INTO users (username, age) VALUES (:c0, :c1), (:c2, :c3);作为查询。

我打开了数据库配置的日志,我看到了:

2014-10-27 16:10:26 Debug: INSERT INTO users (username, age) VALUES (NULL, NULL, 'Array', 'Array')

如果我误解了CakePHP 3.x中使用查询构建器的可能性,请帮助我理解

2 个答案:

答案 0 :(得分:3)

您可以合并多个value()来电:

// ...

foreach($newUsers as $values)
{
    $query->values($values);
}
$query->execute();

或直接修改ValuesExpression对象(可通过Query::clause()访问),其中values()方法允许一次设置所有数据:

// ...

$query->clause('values')->values($newUsers);
$query->execute();

答案 1 :(得分:3)

刚刚测试过。这很有效。

   $newUsers = [
        [
            'username' => 'Felicia',
            'age' => 27,
        ],
        [
            'username' => 'Timmy',
            'age' => 71,
        ],
    ];

    $columns = array_keys($newUsers[0]);

警报!有两种方法可以进行质量插入。这是一种方式:

    $insertQuery = $this->Users->query();

    $newUsersValuesExpression = new ValuesExpression($columns, $insertQuery->typeMap()->types([]));
    $newUsersValuesExpression->values($newUsers);

    $insertQuery->insert($columns)
                ->values($newUsersValuesExpression)
                ->execute();

正如ndm所说,我更喜欢这种方式。

    $insertQuery = $this->Users->query();

    $insertQuery->insert($columns);

    // you must always alter the values clause AFTER insert
    $insertQuery->clause('values')->values($newUsers);

    $insertQuery->execute();