简体   繁体   English

在Propel中将Count添加到SQL查询

[英]add Count to SQL query in Propel

I have in my project old version (1.2) Propel. 我的项目中有旧版本(1.2)Propel。 I would like make query: 我想查询:

SELECT city_id, COUNT(*) FROM House GROUP BY city_id

I tried: 我试过了:

  $c = new Criteria;
  $c->addAsColumn('count', 'Count(' . HousePeer::CITY_ID . ')'); 
  $this->results = HousePeer::doSelect($c);  

but this not working - return me only first record from database, without count etc. 但这不起作用-仅从数据库返回我的第一条记录,没有计数等。

i tried also: 我也尝试过:

$con = Propel::getConnection();
$sql = "SELECT city_id, COUNT(*) FROM House GROUP BY city_id";
$stmt = $con->createStatement();
$rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_NUM);
$this->results = HousePeer::populateObjects($rs);

but this throw me 但这把我丢了

Error populating House object [wrapped: Invalid resultset column: 3]

I would like only receive same as in SQL table: 我只希望收到与SQL表相同的内容:

city_id | count
1       | 2
2       | 4
3       | 3

etc 等等

or get name City from CityPeer (i have correctly relations between City and House) for example: 或从CityPeer(我在City和House之间有正确的关系)获得名称City,例如:

city       | count
New York   | 2
Paris      | 4
Washington | 3

but i can't use this query in Propel. 但我不能在Propel中使用此查询。

You have a great example in the old snippet from symfony. 在symfony的旧代码片段中,您有一个很好的例子

Try: 尝试:

$c = new Criteria;
$c->clearSelectColumns()->addSelectColumn(HousePeer::CITY_ID);
$c->addGroupByColumn(HousePeer::CITY_ID);
$c->addAsColumn('numCity', 'COUNT('.HousePeer::CITY_ID.')');
$c->addJoin(HousePeer::CITY_ID, CityPeer::ID);

$rs = HousePeer::doSelectRS($c);

while ($rs->next())
{
  // etc ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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