简体   繁体   中英

how to convert this query in yii framework model

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
$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

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'
          )
      );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM