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 守护进程/worker 环境 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- HTTP 与 FTP 上传 2021-01-01