0

我正在尝试使用 counterCache 行为将平均“星级”评级从评论表更新到它所属的配置文件表。

这是我的评论表:

class ReviewsTable extends Table
{
    public function initialize(array $config)
    {
        $this->table('reviews');
        $this->displayField('name');
        $this->primaryKey('id');
        $this->addBehavior('Timestamp');
        $this->addBehavior('Ceeram/Blame.Blame');
        $this->belongsTo('Profiles', [
            'foreignKey' => 'profile_id',
            'joinType' => 'INNER'
        ]);
        $this->addBehavior('CounterCache', [
            'Profiles' => [
                'rating_avg' => function($event, $entity, $table){
                    $reviews = $this->find();
                    $avg = $reviews->func()->avg('stars');
                    return $avg;
                }
            ]
        ]);
    }

Profiles 表有一个 'rating_avg' decimal(2,1) ,Reviews 表有一个 'stars' int 列。

当我为“星”添加带有整数值的评论时,我收到一个致命错误:

Error: [PDOException] SQLSTATE[HY000]: General error: 1111 Invalid use of group function

我不知道“组”功能在哪里使用。

错误发生后,DebugKit 的 SQL 日志中显示如下:

INSERT INTO reviews (
  created, modified, created_by, profile_id, 
  content, stars, title
) 
VALUES 
  (
    '2016-03-11 17:17:35', '2016-03-11 17:17:35', 
    38, 1, '', 4, 'check him out'
  )

UPDATE 
  profiles 
SET 
  rating_avg = (
    AVG(stars)
  ) 
WHERE 
  id = 1
4

1 回答 1

0

这是因为你有一个数据数组,你需要添加一个 where() 和集合来获取数据.....这是我用于网站的一个例子......改变和使用你需要的东西

$this->addBehavior('CounterCache', [
            'Profiles' => [
                'rating_avg' => function ($event, $entity, $table) {


                    $response = $this->find()->where(['profile_id'=>$entity->profile_id])->ToArray();
                    $countratings=count($response);

                        $collection=$response;
                        $collection = new Collection($collection);
                        $sumrating=$collection->sumOf('stars');
                                if ($sumrating <> 0 && $countratings <> 0) {
           $RatePer5=(($sumrating/$countratings)*100)/5;
        }else{
            $RatePer5="0";
        }



                    return $RatePer5;


                }
            ]
        ]);
于 2016-09-08T08:21:43.443 回答