Converting HAS_MANY relationship to HAS_ONE

Say each post has comments and ratings…and it’s a has_many relationship

I’m trying to do a $post->comments(array(‘select’=>‘COUNT(id) AS total_comments, SUM(rating) AS total_comment_rating’)), but it’s returning an array of comment objects even though there’s just one.

Is there a better way of doing this?

Thanks

In the relation you should create a new relation with self::STAT (if you want the number of comments for a new for example):


'nbComment'=>array(self::STAT, 'comments', 'id_news'),

So when you call $news->nbComment you’ll have the number of comments for this news.

If you need an average (for a rating for example) you can just add the select you are doing by default the select is a count (as we have seen above) but you can choose an AVG, SUM or MAX:


'average' => array(self::STAT, 'Rating', 'id_news', 'select' => 'AVG(rating)'),

I hope this is answering your question!

I know of that…but let’s say I want the Average AND Count in the same query, ie ‘select’=> ‘AVG(rating) as avg_rating, COUNT(id) AS total_ratings, MAX(rating) AS highest_rating’ etc… STAT will only give you one option

Oh, I have no idea how to do it, but if you find an answer, i’m really interested to know it!