如何将模型数据对象数组转换为dataProvider [英] How to convert model data objects array to dataProvider

查看:191
本文介绍了如何将模型数据对象数组转换为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()),
));

现在使用它会出现错误

未定义属性"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文档中的以下示例).我怀疑您的关系中的属性比提供的代码错误.重新检查关系定义是否可以

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆