【问题标题】:How to make my Model class use postgresql sequence in CakePHP 2.x?如何让我的模型类在 CakePHP 2.x 中使用 postgresql 序列?
【发布时间】:2014-01-10 21:43:35
【问题描述】:

按照Cakephp (2.x) Blog Tutorial,我在Postgresql 9.x中创建了表posts

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]: Not null 违规,在以下内容中抱怨 id 为空:

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

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

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 序列?

【问题讨论】:

    标签: php postgresql cakephp-2.0


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      相关资源
      最近更新 更多