Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

sql - Using CakePHP to insert rows into a table with one IDENTITY column only

In an existing post (link below) I already know how to insert a row into a table with one identity column for Microsoft SQL Server.

Inserting rows into a table with one IDENTITY column only

and now I want to use CakePHP to do the same. However when I try the following, the record will not be saved.

$this -> MyModel -> create();
if ($this -> MyModel -> save()) {
    $this -> log('Record is saved', 'debug');
} else {
    // Always run the following
    $this -> log('Record is not saved', 'debug');
}

What would be the CakePHP way to save such record into the table?

The table schema for MyModel is below:

CREATE TABLE [dbo].[my_models] (
    [id] INT NOT NULL PRIMARY KEY IDENTITY
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For demonstration purposes the current model is written as '__THE_CURRENT_MODEL__' which is, of course, not a proper CakePHP model name. Duh!

    public function add() {
        if( $this->request->is('post') ){
            $this->__THE_CURRENT_MODEL__->create();
            if( $this->__THE_CURRENT_MODEL__->save(
                array(
                    '__THE_CURRENT_MODEL__' => array( 'id' => 'NULL' )
                )
            ) ){
                $this->Flash->success(__('The __current_model__ has been saved.'));
                return $this->redirect( array( 'action' => 'index' ) );
            }else{
                $this->Flash->error(__('The __current_model__ could not be saved. Please, try again.'));
            }
        }
    }

As you should note - the value 'NULL' is not NULL .. which would result in no query at all - the id column is numeric.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...