【问题标题】:Retrieving inserted IDs from saveAll() in CakePHP从 CakePHP 中的 saveAll() 检索插入的 ID
【发布时间】:2012-04-03 21:37:57
【问题描述】:

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

【问题讨论】:

    标签: php cakephp cakephp-1.3 cakephp-model


    【解决方案1】:

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

    
    class AppModel extends Model {
        var $inserted_ids = array();
    
        function afterSave($created) {
            if($created) {
                $this->inserted_ids[] = $this->getInsertID();
            }
            return true;
        }
    }
    

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

    
    if($this->Post->saveAll($posts)) {
        $post_ids=$this->Post->inserted_ids; //contains insert_ids
    }
    

    希望对你有帮助

    【讨论】:

    • Thanx Sudhir,我试过了,但它抛出了一个错误 Undefined property: AppModel:inserted_ids in my controller,这可能是什么原因..??
    • @vin.it 删除 $inseted_ids 之前的 var
    • @ehtesham:thanx ehtesham.i 试过了,但它仍然抛出同样的错误。还有其他可能吗?
    • 在 Stack Overflow 回答中看到从自己的博客复制和粘贴的代码很酷:D
    • 是的,它应该可以在 atomic 选项设置为 true 时正常工作。
    猜你喜欢
    • 1970-01-01
    • 2011-11-02
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多