本文介绍了从CakePHP中的saveAll()检索插入的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using saveAll() to save multiple records in CakePHP, I am able to save them successfully in a table. But the problem arises while retrieving the IDs of those saved rows. LastInsertID() returns only a single last ID here. How can I get all the last inserted IDs which I have inserted using saveAll()?

推荐答案

afterSave 函数在每个人保存saveAll执行后调用,因此你可以这样做:
在你的AppModel

afterSave function is called after each individual save in a saveAll execution, so you could do:In your AppModel


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

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

您可以将此代码放入任何模型,工作良好。然后返回控制器中saveAll之后的ID,如下所示:

You can place this code into any model and it should work fine. Then to return the IDs after the saveAll in your controller, you would do so like this:


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

希望它有帮助

这篇关于从CakePHP中的saveAll()检索插入的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 13:22