krak3n
(Chris)
March 6, 2009, 12:03pm
1
Hi, hope your days at work are not as dull as mine, means I get to play around with Yii so yey lol
Is it possible to simply count related records as a pose to selecting them? For example, something like:
<?php
Post::model()->with(array(
'author'=>array('select'=>'id, name'),
'comments'=>array('count' => 'id', 'condition'=>'approved=1'),
))->findAll();
Or is there an alternate technique?
Thanks
Chris
qiang
(Qiang Xue)
March 6, 2009, 12:06pm
2
Yes you can with 1.0.3. Simply replace findAll() with count().
krak3n
(Chris)
March 6, 2009, 12:31pm
3
That's not really what I'm trying to achieve.
Basically when I list out My Posts I'd like to display a number of comments and not get the comment data just a number of comments related to a post as well as the post data, eg.
array(
[0] = array(
[id] => 'Post title',
['text'] => 'The content of the post',
['comments'] => 15
)
)
Perhaps I should really be storing the number of comments in the posts table itself, would save an extra query I guess.
Chris
canglan
(Canglan)
March 6, 2009, 4:25pm
4
Quote
Perhaps I should really be storing the number of comments in the posts table itself, would save an extra query I guess.
I wouldn't do that, redundant data should be avoided unless the advantages outweigh the disadvantages, which I don't think is the case here .
The good news is that Qiang has just committed an update to the 1.0 branch.
This allows you to do the following.
In the Post model:
<?php
public function relations()
{
return array(
'user' => array(self::BELONGS_TO, 'User', 'user_id'),
'comments' => array(self::HAS_MANY, 'Comment', 'post_id'),
'comments_count' => array(
self::HAS_MANY,
'Comment',
'post_id',
'select' => 'COUNT(??.id) AS count',
'group' => 'post_id',
),
);
}
Then in the view file you can:
<?php echo $post->comments_count[0]->count ?>
I know, it's not the most beautiful piece of code, but it works.
Qiang and Wei are working on SQLMap which is going to support sub-selects, so the future is looking bright.
krak3n
(Chris)
March 6, 2009, 5:45pm
5
Thank you
I shall have a play at the weekend, for now it is my hour and a half journey home lol
qiang
(Qiang Xue)
March 16, 2009, 12:51am
6
I just implemented a new feature called statistical query. With this feature, you can declare relations as follows,
<?php
public function relations()
{
return array(
'user' => array(self::BELONGS_TO, 'User', 'user_id'),
'comments' => array(self::HAS_MANY, 'Comment', 'post_id'),
'comments_count' => array(self::STAT, 'Comment', 'post_id'),
);
}
Then, you can retrieve the comment count using $post->comments_count, or in an eager approach,
<?php
$posts=Post::model()->with('comment_count')->findAll();