3

我的表中有一个自定义查找器方法,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')

但是,数据在任何返回的实体中都不可用。我在哪里可以找到我的汇总数据?

4

1 回答 1

2

此后,我对此进行了一些重构,并将保龄球小门移到他们自己的自定义查找器中,以在此查找器中使用。

以下是我使用 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);
}
于 2014-12-16T14:37:44.770 回答