【发布时间】: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