7

$articles我有一个这样的数组

[
    (int) 0 => [
        'id' => '-@940039',
        'xe_dsca' => 'ÜP2768G/1',
        'xe_citg' => '1F0200',
        'xe_cuni' => 'stk',
        'xe_seak' => 'ÜP2768G/1',
        'xe_seab' => '',
        'xe_wght' => '0.0153',
        'xe_cwun' => 'kg',
        'xe_wgap' => '2',
        'xe_seri' => '2',
        'xe_ltct' => '2',
        'xe_qual' => '2',
        'xe_hama' => '2',
        'xe_ctyo' => 'DE',
        'xe_ccde' => '85045095',
        'xe_cpln' => '240000',
        'xe_spar' => '2',
        'xe_wear' => '2',
        'xe_ctyo_de' => null,
        'xe_cean' => null,
        'xe_ewm_dsce' => null,
        'xe_cood' => null,
        'xe_ewm_dsne' => null,
        'xe_ewm_dsge' => null,
        'xe_ewm_dsen' => null,
        'xe_ewm_dscz' => null,
        'xe_wgh1' => null,
        'xe_wgh2' => null,
        'xe_wgh3' => null
    ],
    (int) 1 => [
        'id' => '000-000500-00000',
        'xe_dsca' => 'DUMMY ZEITBUCHUNG',
        'xe_citg' => '1F0800',
        'xe_cuni' => 'stk',
        'xe_seak' => 'DUMMY ZEITBUCHUN',
        'xe_seab' => '000-000500-00000',
        'xe_wght' => '0',
        'xe_cwun' => 'kg',
        'xe_wgap' => '2',
        'xe_seri' => '2',
        'xe_ltct' => '2',
        'xe_qual' => '2',
        'xe_hama' => '2',
        'xe_ccde' => '000',
        'xe_cpln' => '930000',
        'xe_spar' => '2',
        'xe_wear' => '2',
        'xe_ctyo' => null,
        'xe_ctyo_de' => null,
        'xe_cean' => null,
        'xe_ewm_dsce' => null,
        'xe_cood' => null,
        'xe_ewm_dsne' => null,
        'xe_ewm_dsge' => null,
        'xe_ewm_dsen' => null,
        'xe_ewm_dscz' => null,
        'xe_wgh1' => null,
        'xe_wgh2' => null,
        'xe_wgh3' => null
    ]

在我的控制器中,我有这些行

foreach ($articles AS $article) {
    $query = $this->Articles->query();
    $query
        ->insert($required_article_fields)
        ->values($article)
        ->execute();
}

这段代码工作正常,但是有没有人建议我如何在重复键更新时插入?一次保存多行数据的最佳做法是什么?

4

2 回答 2

17

您可以使用查询epilog()方法

foreach ($articles AS $article) {
  $query = $this->Articles->query();
  $query
    ->insert($required_article_fields)
    ->values($article)
    ->epilog('ON DUPLICATE KEY UPDATE field=field+1')
    ->execute();
}

如果需要安全地传递值,还可以将 QueryExpression 对象传递给方法。

于 2014-07-28T08:10:25.617 回答
5

正如https://stackoverflow.com/a/26590483/80353所建议的那样

你可以做

$query = $this->Articles->query();
$query->insert($required_article_fields);


// need to run clause('values') AFTER insert()
$valuesExpression = $query->clause('values')->values($articles);

$query->values($valuesExpression)
      ->epilog('ON DUPLICATE KEY UPDATE `field1`=VALUES(`field1`) ... ')
      ->execute();

我没有填写您要更新的所有字段,因为我不知道哪个字段是您的唯一索引的一部分。

于 2014-10-27T17:29:20.237 回答