我有两张桌子,'用户'和'帖子',看起来像这样:
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.')
没有任何身份证明......
答案 0 :(得分:3)
你需要这样做:
// In PostsController
public function create()
{
if($this->request->is('post'))
{
$this->request->data['Post']['user_id'] = $this->Auth->user('id');
$this->Post->create();
if($this->Post->save($this->request->data)
{
// Success
}
}
}
答案 1 :(得分:0)
我只是在这里复制这本书,我根本没用过cakePHP!
根据这本书:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html然后有一个&#39; hasMany&#39;关系应该类似于:
class User extends AppModel {
public $hasMany = array(
'Recipe' => array(
'className' => 'Recipe',
'conditions' => array('Recipe.approved' => '1'),
'order' => 'Recipe.created DESC'
)
);
}
你有:
public $ hasMany = array(&#39; Post&#39;);
你的名字应该提一下吗? 即。
public $hasMany = array(
'Post' => array(
'className' => 'Post'
)
);
通过这个,ORM可以计算出类的关联方式以及在运行时填写的内容。