【问题标题】:PHPActiveRecord group option breaks count functionPHPActiveRecord 组选项中断计数功能
【发布时间】:2014-06-09 22:42:09
【问题描述】:

我有一个 PHP ActiveRecord 模型,其中我有一个函数,该函数需要查询返回的行数。我使用内置的static::count($conditions) 函数获取行数。这很好用,但是当我包含 GROUP BY 语句时就会出现问题。当我包含这个时,计数返回 1。我检查了生成的 SQL,它类似于

 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 语句时,我应该得到值 1,000。

很明显,这是因为 COUNT 是一个聚合函数,它不能很好地与 group by 配合使用。话虽如此,如何使用 group by 的 activerecord 返回正确的行数?

【问题讨论】:

    标签: php activerecord phpactiverecord


    【解决方案1】:

    我遇到了同样的问题。我遵循@jvenema 在this question 中设置的示例,其中定义了一个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 创建的行的COUNT(),而不是SUM()。这是为了考虑$has_many$options['joins'] 起作用的情况,以防止INNER JOIN 为关联返回多个结果时重复计算。

    【讨论】:

    • 您需要is_hash 函数才能使此代码正常工作。
    猜你喜欢
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 2021-11-20
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    相关资源
    最近更新 更多