【发布时间】:2014-09-23 08:39:13
【问题描述】:
我对 cakephp 2.x 和模型的关系有一些问题,我有 3 个模型,帖子、用户和评论。 我想将帖子与他的用户绑定,并将评论与他的用户绑定。
在后期模型中:
$belongsTo = array('Comment','User'),
$hasMany = array('CommentOfPost'=>array('className'=>'Comment'));
我有帖子与用户绑定,以及帖子中的所有评论,但我没有 cmets 的用户。
编辑:
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 和他的用户和 Post 和他的 cmets 但不是 cmets 的用户之前的结果相同
现在是我的模特帖子
$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 中使用分页查询
$this->Paginator->settings = $this->paginate;
$data = $this->Paginator->paginate('Post');
$this->set('posts', $data);
编辑:
我的分页参数
$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);
...
}
感谢你们的帮助,你们太棒了!
【问题讨论】:
-
能否提供您的
find()表达式? -
你能追加到你的分页参数数组
'recursive' => 2吗? -
你在你的 AppModel 中使用 Containable 行为吗?
-
不,我不使用,我什至尝试使用
findById()我得到了他的用户和评论的好帖子,但不是用户 cmets 我尝试使用$this->Post->recusrive = 2;但没有效果......我想我我很傻
标签: php cakephp frameworks cakephp-2.x