我有两个表,“用户”和“帖子”,如下所示:
users:
- id
- username
- password
...
posts:
- id
- user_id (foreign key referencing users.id)
- text
基本上,一个用户有多个帖子(博客类型的帖子)。现在,我正在尝试以登录用户的身份创建一个新帖子,但我无法让它工作。这是我所做的:
// 'User' model
class User extends AppModel
{
public $name = 'User';
public $hasMany = array('Post');
...
// 'Post' model
class Post extends AppModel
{
public $name = 'Post';
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
// In PostsController
public function create()
{
if($this->request->is('post'))
{
$this->Post->create();
if($this->Post->save($this->request->data)
{
// Success
}
}
}
// In the post view
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('Post', array('action' => 'create')); ?>
<fieldset>
<legend>
<?php echo __("Write a post"); ?>
</legend>
</fieldset>
<?php echo $this->Form->end(__('Post')); ?>
如果我写了一篇文章并单击“发布”,我会违反完整性约束:
Error: SQLSTATE[23000]: Integrity constraint violation:
1452 Cannot add or update a child row: a foreign key
constraint fails (`yams`.`posts`, CONSTRAINT `user_id`
FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION)
我在这里错过了什么吗?看起来用户 ID 没有保存到模型中。
编辑:
我忘了提,数据库错误还打印出明显错误的 SQL 查询:
INSERT INTO `yams`.`posts` (`text`) VALUES ('this is a test post.')
什么身份证都没有...