How to convert model data objects array to dataProvider(如何将模型数据对象数组转换为 dataProvider)
问题描述
假设我有模型 User
,它与自身具有多对多的关系,名为 friends
.所以 $user->friends
(或 $model->friends
在视图中)给了我一个 User
对象的数组.我想将朋友显示为 gridview.但是 CGridView
数据作为 dataProvider
对象.谷歌搜索找到了将模型对象数组转换为 dataProvider
对象的方法,如下所示.
Suppose I have model User
which have many to many relation to itself named as friends
.
so $user->friends
(or $model->friends
in view) gives me an array of User
objects. I wanted to display the friends as gridview. But CGridView
data as dataProvider
object. Googling for it found the way to convert array of model objects to dataProvider
object as given below.
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'gridUser',
'dataProvider' => new CArrayDataProvider($model->friends, array()),
));
现在使用这个我得到一个错误
Now using this I get an error
未定义属性User.id".
Property "User.id" is not defined.
更新
public function relations()
{
return array(
'friends' => array(self::MANY_MANY, 'User', 'friendship(user_id, friend_id)'),
);
}
推荐答案
我使用两阶段构建如下所示的提供程序.但是我发现它在分页方面给您带来了麻烦.由于在做其他事情,所以我没有费心去解决这个问题
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,
));
话虽如此,您的代码应该可以工作(请参阅下面来自 API 文档的示例).我怀疑您的关系中存在比提供的代码错误的属性.重新检查关系定义是否ok
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
来自 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,
),
));
这篇关于如何将模型数据对象数组转换为 dataProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将模型数据对象数组转换为 dataProvider


- PHP - if 语句中的倒序 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01