CakePHP - Why does Model::save cause() an INSERT instead of an UPDATE?

前端 未结 1 1346
你的背包
你的背包 2020-12-21 15:16

I want to update database in CAKEPHP\'s Way this is my controller

$data = array(
\'KnowledgeBase\' => array(
\'kb_title\' => $this->data[\'Knowledge         


        
相关标签:
1条回答
  • 2020-12-21 15:37

    You do not supply a primary key value, that's why.

    No matter what your primary key is named (Model::$primaryKey), on the model object you have to use the id property (Model::$id) if you want to set the primary key value.

    $this->KnowledgeBase->id = $this->data['KnowledgeBase']['id_kb'];
    

    Internally the model maps this to the appropriate primary key field.

    In the data however you'd use the actual primary key name:

    'id_kb' => $this->data['KnowledgeBase']['id_kb']
    

    btw, I'm not sure why you are (re)building the data array, but if it's to make sure that only specific fields are saved, then you could use the fieldList option instead:

    $this->data['KnowledgeBase']['kb_last_update'] = date('Y-m-d G:i:s');
    
    $options = array(
        'fieldList' => array(
            'kb_title',
            'kb_content',
            'kb_last_update',
            'kb_segment'
        )
    );
    
    $this->KnowledgeBase->save($this->data, $options);
    
    0 讨论(0)
提交回复
热议问题