How to convert model data objects array to dataProvider

前端 未结 2 1756
傲寒
傲寒 2021-02-02 00:40

Suppose I have model User which have many to many relation to itself named as friends. so $user->friends (or $model->friends

2条回答
  •  心在旅途
    2021-02-02 01:21

    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

    From Yii docs:

    $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,
        ),
    ));
    

提交回复
热议问题