如何从包含的表中返回sum()?

时间:2014-12-01 16:31:01

标签: cakephp-3.0

我的Matches表中有一个自定义查找器方法,其中包含一些其他表格,我想返回其中一个包含字段的求和值。

到目前为止,我有以下内容。

/**
 * Custom finder to find the latest matches played
 *
 * @param Query $query
 * @param array $options
 * @return $this
 */
    public function findLatestMatches(Query $query, array $options) {
        return $query->contain([
                'Venues' => function ($q) {
                    return $q->select(['id', 'name', 'location']);
                },
                'Formats' => function ($q) {
                    return $q->select(['id', 'name']);
                },
                'Teams' => [
                    'Clubs' => function ($q) {
                        return $q->select(['id', 'image', 'image_dir']);
                    }
                ],
                'Innings' => [
                    'InningsTypes',
                    'Batsmen' => function ($q) {
                        /* @var \Cake\ORM\Query $q */
                        return $q->select(['totalRuns' => $q->func()->sum('runs')]);
                    },
                    'Bowlers',
                    'Wickets' => function ($q) {
                        /* @var \Cake\ORM\Query $q */
                        return $q->select(['totalWickets' => $q->func()->count('id')]);
                    }
                ]
            ])
            ->order(['when_played' => 'DESC']);
    }

此代码执行正常并且不会产生任何错误。另外,检查DebugKit中的SQL选项卡会将sql显示为已执行。

SELECT (SUM(runs)) AS `totalRuns` FROM batsmen Batsmen WHERE Batsmen.innings_id in ('841fce60-0178-450f-99e8-ad1670f5c84f','93daddf5-256b-4420-b636-0db626baae72','b398d1a0-2c7d-41f7-b2c3-8ea00ddfcece','f949bb45-3d8b-46f5-8967-cc1340a9c1e7')

但是,任何返回的实体都无法获得数据。我在哪里可以找到我的汇总数据?

1 个答案:

答案 0 :(得分:2)

我已经对此进行了一些重构,并将Bowlers小门移到他们自己的定制发现器中,以便在此取景器中使用。

以下是我与Bowlers定制发现者的接触方式。

public function findBowlersWickets(Query $query, array $options)
{
    return $query->contain([
        'Innings' => [
            'Wickets' => [
                'PlayerBowledWicket',
            ]
        ]
    ])
        ->select(['totalWickets' => $query->func()->count('*')])
        ->matching('Innings.Wickets.PlayerBowledWicket', function ($q) {
            return $q->where([
                'AND' => [
                    'Wickets.bowler_player_id = Bowlers.player_id',
                    'Wickets.innings_id = Innings.id'
                ]
            ]);
        })
        ->group(['Innings.id', 'Bowlers.player_id'])
        ->order(['totalWickets' => 'DESC'])
        ->autoFields(true);
}