php - Count Relational Table Rows -
i'm trying count number of rows in relational table many many
, returns wrong value. when 1, returns 2.
ps: models , foreign keys in mysql configured correctly.
comments table:
id | name 10 comment test
users table:
id | name 20 user test
likes (comment/user) many many:
user_id | comment_id 20 10
code:
$criteria = new cdbcriteria; $criteria->select='*, count(likes.id) count_likes'; // believe error in use of count (likes.id). $criteria->with=array('likes'=>array('on'=>'user_id=20')); $model = comments::model()->findbypk($_get['id'], $criteria); // return wrong value echo $model->count_likes; // return 2 should 1. (i need use case) echo count($model->likes); // return right value 1.
you should use statistical query, e.g. :
in comments model :
public function relations() { return array( // ... // assume relation table's name "likes" 'likes'=>array(self::many_many, 'users', 'likes(comment_id, user_id)'), 'likescount'=>array(self::stat, 'users', 'likes(comment_id, user_id)'), // ... ); }
Comments
Post a Comment