所以我有点迷路了。
假设我有以下简单的模型:
岗位
身份证件
内容
评论
身份证件
内容
邮政ID
因此,波斯特有很多评论,我认为这种关系应该是相当明显的描述。
如果我想得到所有的评论,然后在其中得到一个特定的评论呢?就像我想显示一个帖子的评论列表,但是只显示其中一个的内容(通过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);

还是我需要再次在评论上用我自己的循环?
我真的只是想利用yii所提供的优势,然后再编写额外的代码。文档总是假设您总是需要所有的关系数据,而不是指定如何挑选关系数据的一部分。

最佳答案

第一个问题的答案是

$post = Post::model()->with('comments')->find('t.id = :post_id AND comments.id = :comment_id', array(
    ':post_id' => $somePostId,
    ':comment_id' => $someCommentId,
));


$post =  Post::model()->findByPk($somePostId);
$comments = $post->comments(array(
    'condition' => 'comments.id = :comment_id',
    'params' => array(':comment_id' => $someCommentId),
));

第二个问题:你说的“下一个”和“上一个”是什么意思?
在什么旁边?识别或创建时间?
您可以这样做(对于上一个创建时间):
$post =  Post::model()->findByPk($somePostId);
$comment = Comment::model()->findByPk(someCommentId);
$previousComment = $post->comments(array(
    'condition' => 'comments.create_time < :comment_create_time',
    'params' => array(':comment_create_time' => $comment->create_time),
    'limit' => 1,
));

您可以从here的官方课程参考中获取有关此主题的更多信息。
更新
如果要从数据库获取所有注释,而不是通过id获取注释,可以这样做:
$post->注释只是一个数组。这样你就可以循环浏览,得到你在主题中描述的内容。
但也可以向post model类(不是注释,因为它是一个数组)添加一个新方法,如“findCommentByID”:
public function findCommentById($id)
{
    foreach ($this->comments as $comment)
        if ($comment->id == $id)
            return $comment;

    return null;
}

09-19 19:23