CakePHP saveAll重复和非重复条目

时间:2014-07-18 14:34:37

标签: cakephp

那么,

我创建了一个具有以下限制的模型

public $validate = array(
        'player_id' => array(
            'rule' => array(
                'checkUnique',
                array(
                    'player_id',
                    'game_id'
                ),
                true
            ),
            'required'      => true,
            'allowEmpty'    => false,
            'on'            => 'create',
            'message'       => 'Same player_id y game_id'
        )
    );

因此,每当我尝试在表格中创建游戏记录时,只有在尚未创建游戏记录时才会创建游戏记录。

所以我在一个控制器中创建了一个动作,它可以获得一个玩家的近期游戏并使用saveAll保存到数据库中。

如果数据库为空,当然没有任何问题。但是如果我收到一些游戏并且之前已经插入了一些游戏,则saveAll会因为某些游戏已经进入数据库而失败。

public function getRecentGames($server = null, $player = null){
    $this->autoRender = false;

    if( !empty($server) && !empty($player) ){
        $r = $this->_getRecentGames($server, $player, $gamesData);
        if ($r['code'] == 200) {
            if ($this->Game->saveAll($gamesData, array('deep' => true))) {
                pr($gamesData);
                prd('Saved');
            } else {
                pr($this->Game->invalidFields());
                prd('Not saved');
            }
        } else {

        }
    }
    return print_r($gamesData, true);
}

基本上saveAll(..)调用内部validateMany(..),它返回false,因为并非每个条目都有效且saveAll不会尝试保存。这是CakePHP的正常行为以及开发人员希望它的工作方式。

那么,我该怎么办?

  • 检查每个游戏并尝试保存吗? foreach ($games as $game) { $this->Model->saveAssociated(..); }

  • 修改saveAll(..)的行为以保存有效游戏,而不是无效游戏。 (你认为这应该是CakePHP的默认行为吗?)

  • 我没有想到的其他解决方案(?)。请告诉我

谢谢

1 个答案:

答案 0 :(得分:0)

这是我能想到的最佳方法:

$validations = $this->Game->validateMany( $gamesData, array('deep' => true, 'atomic' => false) );
for ($i=count($gamesData)-1; $i>=0; $i--) {
    if (!$validations[$i]) {
        unset($gamesData[$i]);
    }
}
if (!empty($gamesData)) {
    $result = $this->Game->saveAll($gamesData, array('deep' => true, 'validate' => false));
}
相关问题