我有一个PHP ActiveRecord模型,其中有一个函数要求查询返回的行数。我使用内置的static::count($conditions)函数获得行数。这工作得很好,但是当我包含一个GROUP BY语句时,问题就出现了。当我将其包括在内时,计数将返回1。
SELECT COUNT(*)
FROM TABLE
/* JOINS */
/* WHERE CONDITIONS */
GROUP BY `field`当我手动运行查询时,我得到
1
1
1。。。1
(1,000 times since there are 1,000 rows in the DB)当我删除GROUP BY语句时,我得到了应该得到的值1000。
显然,这是因为COUNT是一个聚合函数,并且它不能很好地与group by配合使用。那么,我如何使用activerecord和group by返回正确的行数呢?
发布于 2015-02-16 14:12:04
我也有同样的问题。我遵循了this question中@jvenema设置的示例,其中一个定义了一个BaseModel类来覆盖默认的ActiveRecord\Model行为。然后,您的模型将扩展BaseModel类。
class BaseModel extends ActiveRecord\Model
{
public static function count(/* ... */)
{
$args = func_get_args();
$options = static::extract_and_validate_options($args);
// Call the original function if $options['group'] is undefined
if ( !array_key_exists('group', $options) )
return call_user_func_array( 'parent::count', func_get_args() );
// This might fail if the table has a `counts` column
$options['select'] = 'COUNT(*) as counts';
if (!empty($args) && !is_null($args[0]) && !empty($args[0]))
{
if (is_hash($args[0]))
$options['conditions'] = $args[0];
else
$options['conditions'] = call_user_func_array('static::pk_conditions',$args);
}
$table = static::table();
$sql = $table->options_to_sql($options);
$values = $sql->get_where_values();
// Again, this might fail if there is a table named `tmp`
$wrapper = "SELECT COUNT(counts) FROM ({$sql->to_s()}) as tmp";
// Casting to (int) is optional; remove if it causes problems
return (int) static::connection()->query_and_fetch_one($wrapper,$values);
}
}仅当设置了$options['group']时,此函数才会触发。此外,请注意,这将执行由GROUP BY而不是SUM()创建的行的COUNT()。这是为了应对$has_many和$options['joins']正在运行的情况,以防止INNER JOIN为一个关联返回多个结果时出现重复计数。
https://stackoverflow.com/questions/24130200
复制相似问题