如何在yii框架模型中转换此查询

时间:2011-02-10 11:34:50

标签: php sql yii

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

2 个答案:

答案 0 :(得分:4)

$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();

或者如果您有用户模型(我认为这将有效 - 我没有测试其中任何一个;)

$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

答案 1 :(得分:1)

尚未测试过。但它可以像这样工作

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