Вопрос

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

Это было полезно?

Решение

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

Другие советы

I am just copying the book here, i have not used cakePHP at all!

According to the book: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html then a 'hasMany' relationship should look similar to:

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

You have:

public $hasMany = array('Post');

Should there be mention of a classname in yours? i.e.

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

With this then the ORM can work out how the classes relate and what to fill in at run time.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top