沃梦达 / 编程问答 / php问题 / 正文

如何将模型数据对象数组转换为 dataProvider

How to convert model data objects array to dataProvider(如何将模型数据对象数组转换为 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

基础教程推荐