使用CakePHP将行插入到仅包含一个IDENTITY列的表中

使用CakePHP将行插入到仅包含一个IDENTITY列的表中

本文介绍了使用CakePHP将行插入到仅包含一个IDENTITY列的表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在现有的帖子(下面的链接)中,我已经知道如何插入一行到Microsoft SQL Server的一个标识列。



现在我想使用CakePHP做同样的事情。但是,当我尝试以下操作时,将不会保存该记录。

  $ this  - MyModel  - >创建(); 
if($ this - > MyModel - > save()){
$ this - > log('Record is saved','debug');
} else {
//始终运行以下
$ this - > log('Record is not saved','debug');
}

CakePHP如何将这种记录保存到表中? p>

MyModel的表模式如下:

  CREATE TABLE [dbo] 。[my_models](
[id] INT NOT NULL PRIMARY KEY IDENTITY


不一个正确的CakePHP模型名称。 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(__('__current_model__已保存。
return $ this-> redirect(array('action'=>'index'));
} else {
$ this-> Flash->错误(__('__current_model__无法保存,请重试。
}
}
}

'NULL'不是 NULL ..这将导致根本没有查询 - ID列数字


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
)
解决方案

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.

这篇关于使用CakePHP将行插入到仅包含一个IDENTITY列的表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 14:42