我有两个表,“用户”和“岗位”,看起来像这样:如何将用户ID用作外键?
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.')
有没有任何的ID ...
看看是否有帮助。 http://stackoverflow.com/a/16805528/1003917 –
Post模型中的$ belongsTo变量不需要指定foreignKey - 如果不指定任何其他内容,CakePHP将自动查找名为“user_id”的列 – jackel414
你是否允许在帖子表中的user_id字段中为空? – makallio85