how to convert this query in yii framework model

2020-05-06 06:48发布

问题:

SELECT u.id, u.username, u.score, 
(SELECT COUNT(ownerId) FROM post p WHERE p.ownerId = u.id) AS totalPost 
FROM users u 
ORDER BY u.score DESC, totalPost DESC LIMIT 10

回答1:

$sql = "SELECT u.id, u.username, u.score, ".
   "(SELECT COUNT(ownerId) FROM post p WHERE p.ownerId = u.id) AS totalPost ".
   "FROM users u ".
   "ORDER BY u.score DESC, totalPost DESC ".
   "LIMIT 10";
$command=Yii::app()->db->createCommand($sql);
$results=$command->query();

or if you have a User model (I think this will work - I didn't test either of these ;)

$criteria = new CDbCriteria();
$criteria->select = "t.id, t.username, t.score, (SELECT COUNT(ownerId) FROM post p WHERE p.ownerId = t.id) AS totalPost";
$criteria->order = "u.score DESC, totalPost DESC";
$criteria->limit = "10";
$results = User::model()->findAll($criteria); // this returns an array of User models


回答2:

Haven't tested it. But it could work like this

$user = User::model()
      ->with('post')
      ->findAll(
          array(
            'select'=>array('id','username','score','totalPost'=>'count(ownerId)'),
            'group'=>'id',
            'order'=>'score DESC,totalPost DESC'
          )
      );


标签: php sql yii