Converting custom sql query in to a dataprovider yii?
我正在尝试将以下查询转换为数据提供程序,以便它可以显示在 CGridView 中。我曾尝试使用 CArrayDataProvider,但到目前为止还没有任何运气,任何帮助将不胜感激!
这里是查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public function getTeamsByLevelIdAndCompetitionId($levelId, $competitionId) { $query ="SELECT t.*, (SELECT COUNT(*) FROM tbl_competition_teams ct WHERE ct.team = t.id AND ct.competition = :competitionId) AS 'inCompetition' FROM tbl_teams t WHERE t.level = :levelId"; $params = array( 'levelId' => $levelId, 'competitionId' => $competitionId ); $result = array(); $teams = $this->findAllBySQL($query, $params); return $teams; } |
这就是我尝试将其放入 CArrayDataProvider 的方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public function getTeamsByLevelIdAndCompetitionId($levelId, $competitionId) { $rawData = Yii::app()->db->createCommand("SELECT t.*, (SELECT COUNT(*) FROM tbl_competition_teams ct WHERE ct.team = t.id AND ct.competition = :competitionId) AS 'inCompetition' FROM tbl_teams t WHERE t.level = :levelId")->queryAll(); $params = array( 'levelId' => $levelId, 'competitionId' => $competitionId ); return new CArrayDataProvider($rawData, array( 'id'=>'id', 'sort'=>array( 'attributes'=>array( 'id', 'title', 'club', 'level', 'inCompetition', ), ), |
));
}
但这给了我错误"CDbCommand未能执行SQL语句:SQLSTATE [HY093]:无效参数号:未绑定参数。"
这是我的团队表
1 2 3 4 5 6 7 |
和我的参赛队桌
1 2 3 4 5 6 7 | CREATE TABLE `tbl_competition_teams` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `competition` int(10) unsigned NOT NULL DEFAULT '0', `team` int(10) unsigned NOT NULL DEFAULT '0', `seasonId` int(11) NOT NULL DEFAULT '3', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=126320 ; |
提前一百万感谢您的任何建议!
也许问题是你 queryAll() 执行查询。此时您没有将值分配给您的参数
1 2 3 4 5 6 7 | $rawData = Yii::app()->db->createCommand("SELECT t.*, (SELECT COUNT(*) FROM tbl_competition_teams ct WHERE ct.team = t.id AND ct.competition = $competitionId) AS 'inCompetition' FROM tbl_teams t WHERE t.level = $levelId")->queryAll(); |
您也可以尝试重写您的查询。
1 2 3 4 5 6 7 8 9 10 11 12 | $query ="SELECT t.*, (SELECT COUNT(*) FROM tbl_competition_teams ct WHERE ct.team = t.id AND ct.competition = :competitionId) AS 'inCompetition' FROM tbl_teams t WHERE t.level = :levelId"; $command= Yii::app()->db->createCommand($query); $command->bindValue(':levelId', $levelId); $command->bindValue(':competitionId', $competitionId); $rawData = $command->queryAll(); |