我有一个团队的一对多关系,它是数据库表中的玩家,我可以从team/view
页面成功查看团队信息。
如何在团队中添加该团队的玩家,如下所示:
Team A
Team A description
Team A players
-----------------------------------------------------------------
| Player Name | Position | Shirt Number | Rating | Date Created |
-----------------------------------------------------------------
| Mike | Striker | 10 | 8 | Jan 13 2016 |
| Ken | Keeper | 1 | 9 | Oct 10 2015 |
-----------------------------------------------------------------
这是我在模型Team.php
public function relations() {
return array(
'players' => array(self::HAS_MANY, 'TeamPlayers', 'teamID'),
'created' => array(self::BELONGS_TO, 'Users', 'createdBy'),
);
}
这是我的控制器controllers/TeamController.php
public function actionView($id)
{
$model = Team::model()->findByPk((int)$id);
if($model === null) {
throw new CHttpException(404,'The requested page does not exist.');
}
$this->render('view',array('model'=>$model));
}
这是views/team/view.php
文件:
<h1><?php echo 'Team '.$model->teamName; ?></h1>
<?php
$this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'teamID',
'teamName',
'teamDescription',
'created.userName',
'dateCreated',
),
));
?>
<h2>Team players</h2>
<?php
$players = $model->players;
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'team-grid',
'dataProvider'=>$players,
'columns'=>array(
'playerName',
'position',
'shirtNumber',
'rating',
'dateCreated'
),
));
?>
这会导致此错误:
Fatal error: Call to a member function getData() on a non-object in /yii-1.1.6/framework/zii/widgets/CBaseListView.php on line 105
这是因为我的view.php文件中的这一行:
'dataProvider'=>$players,
所以我的问题是,如何在我的teamPlayers
文件中获取team/view.php
dataProvider以用于gridview?
答案 0 :(得分:1)
我认为问题是如何创建dataProvider
。使用关系$model->players
数据并未准备好在CGridView
中使用它。
您应该在Team
模型中创建方法,为玩家准备dataProvider。这应该是这样的:
public function getPlayersDataProvider()
{
$count = Yii::app()->db->createCommand('SELECT COUNT(*) FROM TeamPlayers WHERE teamID = :teamId')->queryScalar(array(':teamId'=>$this->id));
$sql = 'SELECT * FROM TeamPlayers WHERE teamID = :teamId';
$rawData = Yii::app()->db->createCommand($sql)->queryAll(true, array(':teamId'=>$this->id));
$dataProvider = new CArrayDataProvider($rawData, array(
'totalItemCount'=>$count,
'id'=>'id',
'pagination'=>array(
'pageSize'=>20,
),
));
return $dataProvider;
}
此方法创建CArrayDataProvider
实例。我在这个方法中使用原始SQL,因为它更容易用数组数据创建CArrayDataProvider
。现在,在您的CGridView
窗口小部件中,将dataProvider
更改为以下内容:
'dataProvider'=>$model->getPlayersDataProvider(),