从CakePHP中的saveAll()检索插入的ID

Vin*_*eet 8 php cakephp cakephp-1.3 cakephp-model

使用saveAll()在CakePHP中保存多个记录,我能够将它们成功保存在表中.但是在检索那些已保存行的ID时会出现问题.LastInsertID()这里只返回一个最后一个ID.如何获取我插入的所有最后插入的ID saveAll()

Sud*_*oti 26

在saveAll执行中的每个单独保存之后调用afterSave函数,因此您可以执行:在您的AppModel中


class AppModel extends Model {
    var $inserted_ids = array();

    function afterSave($created) {
        if($created) {
            $this->inserted_ids[] = $this->getInsertID();
        }
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以将此代码放入任何模型中,它应该可以正常工作.然后在控制器中的saveAll之后返回ID,你会这样做:


if($this->Post->saveAll($posts)) {
    $post_ids=$this->Post->inserted_ids; //contains insert_ids
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你

  • 很酷的看到代码在Stack Overflow答案中从一个人自己的博客中复制和粘贴:D (2认同)