如何使我的Model类在CakePHP 2.x中使用postgresql序列?

时间:2014-01-10 10:16:06

标签: php postgresql cakephp-2.0

Cakephp (2.x) Blog Tutorial之后,我在 Postgresql 9.x 中创建了表帖子

CREATE TABLE posts (
    id INTEGER NOT NULL PRIMARY KEY,
    title VARCHAR(50),
    body TEXT,
    created TIMESTAMP DEFAULT now(),
    modified TIMESTAMP DEFAULT NULL
);

CREATE SEQUENCE posts_id_seq owned BY posts.id;

尝试添加帖子时,我收到 SQLSTATE [23502]:非空违规,抱怨以下内容为空:

INSERT INTO "public"."posts" ("created", "title", "body", "modified") VALUES ('now()', 'x', 'x', '2014-01-10 10:58:49')

发生这种情况是因为在创建操作期间未调用序列。经过一段时间的谷歌搜索后,我发现了我必须specify the sequence命名的建议,或者在我的模型类中创建了一个nextval方法(Post)。不幸的是,这两个建议都未能解决问题。这是我的模型类:

class Post extends AppModel {

    public $sequence = 'posts_id_seq';
    public $validate = array(
        'title' => array(
            'rule' => 'notEmpty'
        ),
        'body' => array(
            'rule' => 'notEmpty'
        )
    );

    public function nextval() {
        $sql = "select nextval('posts_id_seq') as nextval";
        $result = $this->query($sql);
        return $result[0][0]['nextval'];
    }

}

这是被调用的控制器方法:

public function add() {
    if ($this->request->is('post')) {
        $this->Post->create();
        if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash(__('Your post has been saved.'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Unable to add your post.'));
    }
}

有没有办法告诉CakePHP使用posts_id_seq序列?

1 个答案:

答案 0 :(得分:0)

在您的情况下,似乎最简单的解决方案是按如下方式定义表:

CREATE TABLE posts (
    id SERIAL PRIMARY KEY,
    title VARCHAR(50),
    body TEXT,
    created TIMESTAMP DEFAULT now(),
    modified TIMESTAMP DEFAULT NULL
);

SERIAL是执行自动递增整数的pg方式。