Torkashvand
Torkashvand

Reputation: 416

Model Associations don't work correctly

I have two model. PostModel & CommentModel.
I defined two relation in these classes.

<?php
class PostModel extends AppModel {
    var $name = 'Post';
    var $hasMany = array(
        'Comment' => array(
            'className' => 'Comment',
            'foreignKey' => 'post_id'
        )
    );
}
 ?>

and

<?php 
class CommentModel extends AppModel {
var $name = 'Comment';
var $belongsTo = array(
    'Post' => array(
        'className' => 'Post',
        'foreignKey' => 'post_id'
    )
);
}
?>

and in database i have posts table and comments table with post_id column. In the PostController class when i fetch record with this command :

$this->set('post',$this->Post->findById($id)); 

and debug $post array i see this array:

array(
'Post' => array(
    'id' => '4',
    'title' => 'روز اول دانشگاه',
    'body' => 'سلام. روز اول بود که اومده بودیم '
    'created' => '2012-11-11 21:49:48',
    'modified' => null
)
)

I expect that [comment] row be in this array but there isn't.

I search net an debug my app but i can't solve this issue.!!!!!

note : cakephp version is 2.2.3 stable

Upvotes: 1

Views: 158

Answers (2)

elliot
elliot

Reputation: 772

Your models are named incorrectly. PostModel should be Post with a posts table, CommentModel should be Comment with a comments table and a post_id in it. Furthermore, this isn't working because you've told your Comments model to look for a 'post_id' on the posts table as a foreign key. This is not correct for a Posts hasMany Comments relationship, and since that column doesn't exist it's going to fail. If you follow the convention for Models, you don't actually need to pass anything into the arrays. The ORM will figure it out.

class Post extends AppModel {
    public $hasMany = array('Comment');
}
class Comment extends AppModel {
    public $belongsTo = array('Post');
}

Upvotes: 2

mark
mark

Reputation: 21743

Do you use containable? if not, do so!

public $actsAs = array('Containable');

in your model

and then

$this->Post->find('first', array(
    'conditions' => array('Post.id'=>$id), 
    'contain' => array('Comment'));

You should also rename your models as Dave pointed out. So just "Post extends AppModel" (Post.php) and "Comment extends AppModel" (Comment.php) to follow conventions.

PS: you can then drop "var $name" from your models. also remove the closing ?> from your php files. last but not least rename all remaining "var" to "public".

Upvotes: 1

Related Questions