how to convert this query in yii framework model

被刻印的时光 ゝ 提交于 2019-12-20 06:26:33

问题


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


来源:https://stackoverflow.com/questions/4956570/how-to-convert-this-query-in-yii-framework-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!