CakePHP 3 - 按日期(年)选择包含表格的行

时间:2017-07-06 08:30:16

标签: php mysql cakephp

我有一张像下面这样的表,现在我不想按年获得这些行。但是当我尝试这个时,我会收到以下错误:

  

错误:SQLSTATE [42S22]:未找到列:1054未知列'匹配日期'在' where子句'

我和#34;匹配"表

id | goalsfor   | goalsagainst  | date
1  | 5          | 4             | 2017-07-05 15:57:36
2  | 9          | 5             | 2017-07-05 17:06:31
3  | 7          | 8             | 2015-07-05 15:57:36
4  | 0          | 2             | 2014-07-05 15:57:36
6  | 5          | 4             | 2014-07-05 15:57:36
7  | 7          | 9             | 2014-07-05 15:57:36

我的查询:

 $playedMatches = $this->Players
    ->find()
    ->contain([
       'MatchePlayers' => [
          'Matches'
       ]
    ]);

 $playedMatches->where(['YEAR(Matches.date) =' => "2017"]);

我的协会:

class PlayersTable extends Table {

    public function initialize(array $config) {
        parent::initialize($config);

        $this->setTable('players');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->hasMany('MatchePlayers', [
            'className' => 'MatchPlayers',
            'foreignKey' => 'player_id',
            'propertyName' => 'matches',
            'dependent' => true
        ]);
    }
}

class MatchPlayersTable extends Table {

    public function initialize(array $config) {
        parent::initialize($config);

        $this->setTable('matches_players');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->belongsTo('Players', [
            'className' => 'Players',
            'foreignKey' => 'player_id',
            'propertyName' => 'player'
        ]);

        $this->belongsTo('Matches', [
            'className' => 'Matches',
            'foreignKey' => 'match_id',
            'propertyName' => 'match'
        ]);
    }
}

2 个答案:

答案 0 :(得分:2)

我发现你选择的名字令人困惑:MatchPlayers,MatchePlayers ......

无论如何:当你有一个belongsToMany关系时,cake不会执行单个查询(并且一个Player belongsToMany匹配match_players)

所以你必须在include子句中指定你的条件

$playedMatches = $this->Players
->find()
->contain([
    'MatchePlayers.Matches' => function ($q)
    {
        return $q->where(['YEAR(Matches.date) =' => "2017"])
    }
]);

答案 1 :(得分:1)

您的查询中存在错误,您的包含语法错误,请尝试此操作,

$playedMatches = $this->Players
->find()
->contain([
   'MatchePlayers.Matches'
]);
$playedMatches->where(['YEAR(MatchePlayers.Matches.date) =' => "2017"]);

快乐编码:)