我对cakephp 2.x和模型的关系有一些麻烦,我有3个模型,帖子,用户和评论。 我希望将Post与他的用户绑定并与他的用户进行评论。
在帖子模型中:
$belongsTo = array('Comment','User'),
$hasMany = array('CommentOfPost'=>array('className'=>'Comment'));
我有与用户的Post绑定,以及帖子中的所有评论,但我没有评论的用户。
编辑:
Sql输出
1 SELECT `Post`.`id`, `Post`.`title`, `Post`.`content`, `Post`.`tags`, `Post`.`created`, `Post`.`modified`, `Post`.`user_id`, `User`.`id`, `User`.`username`, `User`.`password`, `User`.`role`, `User`.`name`, `User`.`lastname`, `User`.`birthdate`, `User`.`email`, `User`.`created`, `User`.`modified` FROM `blog`.`posts` AS `Post` LEFT JOIN `blog`.`users` AS `User` ON (`Post`.`user_id` = `User`.`id`) WHERE `Post`.`id` = 16 LIMIT 1 1 1 0
2 SELECT `CommentOfPost`.`id`, `CommentOfPost`.`post_id`, `CommentOfPost`.`user_id`, `CommentOfPost`.`content`, `CommentOfPost`.`created` FROM `blog`.`comments` AS `CommentOfPost` WHERE `CommentOfPost`.`post_id` = (16)
编辑: 评论模型
public $belongsTo = array('User' => array('className' => 'User'));
发布模型
public $belongsTo = array('Comment' => array('className' => 'Comment'));
编辑:
感谢回复,我有相同的结果,就像之前我有Post和他的用户和帖子及他的评论但不是评论的用户
现在我的模特帖子
$hasMany = array(
'Comment' => array(
'className' => 'Comment',
)
),
$belongsTo = array(
'User' => array(
'className' => 'User',
)
);
用户模型
$hasMany = array('Comment' => array('className' => 'Comment'));
评论模型
$belongsTo = array('Users' => array('className' => 'User'), 'Posts' => array('clasName' => 'Post'));
我在PostsController中使用paginate查询
$this->Paginator->settings = $this->paginate;
$data = $this->Paginator->paginate('Post');
$this->set('posts', $data);
编辑:
我的paginate params
$paginate = array(
'limit' => 10,
'recursive' => 2,
'order' => array(
'Post.id' => 'desc'
)
);
我尝试使用和不使用递归选项
好的,已经完成了!
简历我有:
class User extends AppModel {
public $hasMany = array('Comment' => array('className' => 'Comment'));
}
class Post extends AppModel
{
$hasMany = array(
'Comment' => array(
'className' => 'Comment',
)
),
$belongsTo = array(
'User' => array(
'className' => 'User',
)
);
}
class Comment extends AppModel {
public $belongsTo = array('User' => array('className' => 'User'), 'Post' => array('clasName' => 'Post'));
}
PostsController extends AppController
{
....
$this->Post->recursive = 2;
$post = $this->Post->findById($id);
...
}
感谢你的帮助,你真棒!
答案 0 :(得分:0)
Post
不属于Comment
。它有很多comments
。
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
食谱中的例子:
class User extends AppModel {
public $hasMany = array(
'MyRecipe' => array(
'className' => 'Recipe',
)
);
}
适合您的申请:
class Post extends AppModel {
public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
)
);
public $belongsTo = array(
'User' => array(
'className' => 'User',
)
);
}