php 如何将模型数据对象数组转换为 dataProvider
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14134653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert model data objects array to dataProvider
提问by prashu132
Suppose I have model Userwhich have many to many relation to itself named as friends.
so $user->friends(or $model->friendsin view) gives me an array of Userobjects. I wanted to display the friends as gridview. But CGridViewdata as dataProviderobject. Googling for it found the way to convert array of model objects to dataProviderobject as given below.
假设我有一个模型User,它与自身有很多关系,命名为friends. 所以$user->friends(或$model->friends在视图中)给了我一个User对象数组。我想将朋友显示为 gridview。但CGridView数据作为dataProvider对象。谷歌搜索找到了将模型对象数组转换为dataProvider对象的方法,如下所示。
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'gridUser',
'dataProvider' => new CArrayDataProvider($model->friends, array()),
));
Now using this I get an error
现在使用这个我得到一个错误
Property "User.id" is not defined.
未定义属性“User.id”。
UPDATE
更新
public function relations()
{
return array(
'friends' => array(self::MANY_MANY, 'User', 'friendship(user_id, friend_id)'),
);
}
回答by Stefano Mtangoo
I use two stage building the provider shown below. But I found that it gives you trouble in terms of Pagination. I have not bothered to resolve that problem since am doing other things
我使用两阶段构建如下所示的提供程序。但我发现它在分页方面给你带来了麻烦。我没有费心去解决这个问题,因为我在做其他事情
$dataProvider = new CArrayDataProvider('User');
$dataProvider->setData($model->friends);
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'gridUser',
'dataProvider' =>$dataProvider,
));
That being said, your code should work (see the example below from API docs). I suspect there is wrong attribute in your relations than the provided code. Re-check the relation definition if it is ok
话虽如此,您的代码应该可以工作(请参阅下面来自 API 文档的示例)。我怀疑您的关系中有比提供的代码错误的属性。如果没问题,重新检查关系定义
From Yii docs:
来自 Yii 文档:
$rawData=Yii::app()->db->createCommand('SELECT * FROM tbl_user')->queryAll();
// or using: $rawData=User::model()->findAll(); <--this better represents your question
$dataProvider=new CArrayDataProvider($rawData, array(
'id'=>'user',
'sort'=>array(
'attributes'=>array(
'id', 'username', 'email',
),
),
'pagination'=>array(
'pageSize'=>10,
),
));
回答by prashu132
Got it :) , i can use CActiveDataProviderinstead of CArrayDataProvideras given below
明白了 :) ,我可以使用CActiveDataProvider而不是CArrayDataProvider下面给出的
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'gridUser',
'dataProvider' => new CActiveDataProvider('User', array(
'data'=>$model->friends,
)),
//...... columns display list.....
));
Anyways thanks for the reply @Stefano
无论如何感谢回复@Stefano

