Search code examples
phpcakephpcakephp-2.4mysql-error-1452

How to use the user ID as a foreign key?


I have two tables, 'users' and 'posts', looking like this:

users:
- id
- username
- password
...

posts:
- id
- user_id (foreign key referencing users.id)
- text

Basically, a user has multiple posts (blog-type posts). Now, I'm trying to create a new post as a logged in user, but I can't get it to work. Here's what I've done:

// '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')); ?>

If I write a post and click 'Post', I get an integrity constraint violation:

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)

Am I missing something here? It looks like the user id is not saved to the model.

EDIT:

I forgot to mention, the database error also prints out the SQL query which is clearly wrong:

INSERT INTO `yams`.`posts` (`text`) VALUES ('this is a test post.')

There's no ID whatsoever...


Solution

  • You need to do this:

    // 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
            }
        }
    }