【发布时间】:2011-11-08 04:27:51
【问题描述】:
所以我对 Yii 中的 CActiveRecord 有点迷失了。
假设我有以下简单模型:
- 发布
- 身份证
- 内容
- 评论
- 身份证
- 内容
- post_id
所以发表 HAS_MANY 评论,我认为从该描述中可以看出这种关系。
如果我想获得所有 cmets,然后在其中获得特定评论,该怎么办?就像我想显示一个帖子的 cmets 列表,但只显示其中一个的内容(通过 PK)。
所以我有:
$this->post = Post::model()->with('comments')->findByPk( $pid );
// this next line is an extra DB Query, right?
$this->comment = Comment::model()->findByPk( $cid );
但我想要类似的东西:
$this->post = Post::model()->with('comments')->findByPk( $pid );
// this is not valid code because the comments is an array
$this->comment = $this->post->comments->findByPk( $cid ); // <---
我是否必须自己将其包装在一个循环中才能第二次实现 findByPk?
我的第二个问题是,我可以执行以下操作吗?
$this->post = Post::model()->with('comments')->findByPk( $pid );
$this->comment = Comment::model()->findByPk( $cid );
// Get the PK of the next and previous comments from the $cid comment
// again, not valid code
$this->next = $this->post->NextComment($this->comment);
$this->prev = $this->post->PreviousComment($this->comment);
或者我是否需要再次将自己的循环包裹在 cmets 上?
在编写额外代码之前,我真的只是想利用 Yii 提供的功能。该文档始终假定您始终需要所有关系数据,它没有指定如何选择部分关系数据。
【问题讨论】:
标签: php activerecord yii