How do I properly save data to the database?

后端 未结 2 1049
余生分开走
余生分开走 2021-01-03 12:04

I normally save new data to the database like this:

$this->MyTable->set(array(
 \'id\' => $id,
 \'code\' => $temp_code,
 \'status\' => $status         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 12:54

    If you want to save new data, just use Model::save():

    $data = array(
        'ModelName' => array(
            'foo' => $foo
        )
    )
    
    // prepare the model for adding a new entry
    $this->ModelName->create();
    
    // save the data
    $this->ModelName->save($data);
    

    If you want to update your data just use the same method without calling Model::create()

    $data = array(
        'ModelName' => array(
            'id' => $id
            'foo' => $foo
        )
    )
    
    $this->ModelName->save($data);
    

    See also: http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-save-array-data-null-boolean-validate-true-array-fieldlist-array

    Edit:

    I guess this is what you're looking for:

    $this->ModelName->id = $id;
    if (!$this->ModelName->exists()) {
        $this->ModelName->create();
    }
    
    $this->ModelName->save($data);
    

提交回复
热议问题