What is the equivalent to getLastInsertId() in Cakephp?

后端 未结 22 610
囚心锁ツ
囚心锁ツ 2020-11-28 11:00

If I do getLastInsertId() immediately after a save(), it works, but otherwise it does not. This is demonstrated in my controller:

f         


        
相关标签:
22条回答
  • 2020-11-28 11:24

    Each time a save method is called on a model, cake internally calls Model::getLastInsertId() and stores the result into model class attribute id, so after calling save() it is not necessary to call Model::getLastInsertId() or inserId(), as tha value can be directly accessed like this

    $id = $this->id;// within a model
    $id = $this->{$this->modelName}->id;// in a controller
    
    0 讨论(0)
  • 2020-11-28 11:26

    In Cake, the last insert id is automatically saved in the id property of the model. So if you just inserted a user via the User model, the last insert id could be accessed via $User->id

    id - Value of the primary key ID of the record that this model is currently pointing to. Automatically set after database insertions.

    Read more about model properties in the CakePHP API Docs: http://api.cakephp.org/2.5/class-AppModel.html

    Edit: I just realized that Model::getLastInsertID() is essentially the same thing as Model->id

    After looking at your code more closely, it's hard to tell exactly what you're doing with the different functions and where they exist in the grand scheme of things. This may actually be more of a scope issue. Are you trying to access the last insert id in two different requests?

    Can you explain the flow of your application and how it relates to your problem?

    0 讨论(0)
  • 2020-11-28 11:26

    Try using this code in your model class (perhaps in AppModel):

    function get_sql_insert_id() {
       $db =& ConnectionManager::getDataSource($this->useDbConfig);
       return $db->lastInsertId();
    }
    

    Caveat emptor: MySql's LAST_INSERT_ID() function only works on tables with an AUTO_INCREMENT field (otherwise it only returns 0). If your primary key does not have the AUTO_INCREMENT attribute, that might be the cause of your problems.

    0 讨论(0)
  • 2020-11-28 11:27

    After insertion of data, we can use following code to get recently added record's id:

        $last_insert_id=$this->Model->id;
    
    0 讨论(0)
  • 2020-11-28 11:30

    each time you perform an insert operation on any model, cake internally fetchesthe last insert Id and Sets to Model->id attribute.

    so one can access it directly by $Model->id;, no need to query again for lastInsertId.

    0 讨论(0)
  • 2020-11-28 11:33

    When you use save(), the last insert ID is set to the model’s $id property. So:

    if ($this->Model->save()) {
        printf('Last insert ID was %s', $this->Model->id);
    }
    
    0 讨论(0)
提交回复
热议问题