1

我有两个表,“用户”和“帖子”,如下所示:

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.')

什么身份证都没有...

4

2 回答 2

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
        }
    }
}
于 2014-03-29T14:30:18.710 回答
0

我这里只是抄书,根本没用过cakePHP!

根据这本书:http ://book.cakephp.org/2.0/en/models/associations-linking-models-together.html那么“hasMany”关系应该类似于:

class User extends AppModel {
    public $hasMany = array(
        'Recipe' => array(
            'className' => 'Recipe',
            'conditions' => array('Recipe.approved' => '1'),
            'order' => 'Recipe.created DESC'
        )
    );
}

你有:

public $hasMany = array('Post');

应该在你的名字中提到一个类名吗?IE

public $hasMany = array(
        'Post' => array(
            'className' => 'Post'
           )
       );

有了这个,ORM 就可以计算出类是如何关联的以及在运行时要填写什么。

于 2014-03-29T14:41:52.477 回答