douhunkuang8955
2016-08-22 13:47
浏览 300
已采纳

Yii2 - 多次使用dataProvider进行不同的排序

So I have a dataprovider which is created in a controller like this:

$modelSearch = new SearchModel();
$data_provider = $modelSearch->search(Yii::$app->request->queryParams); // returns the data provider

Then I use the $data_provider in a view like this:

GridView::widget([
    'dataProvider' => $data_provider,
    'export'       => false,
    'columns'      => [
        ...
    ],
...

But now I'd like to use the same data from the $data_provider but without pagination and other sorting specifications.

Tried this but doesn't work:

$data_provider->sort = ['defaultOrder'=> ['column_a' => SORT_ASC, 'column_b' => SORT_DESC]]
$data_provider->pagination = false;

I think that's because the data is already retrieved with the ->search() method. Do I need to create a whole new search model class? just to get a different sorting?

Thanks in advance!

图片转代码服务由CSDN问答提供 功能建议

所以我有一个数据提供者,它在控制器中创建,如下所示:

  $ modelSearch = new SearchModel(); 
 $ data_provider = $ modelSearch-> search(Yii :: $ app-> request-> queryParams);  //返回数据提供者
   
 
 

然后我在这样的视图中使用$ data_provider:

  GridView  :: widget([
'dataProvider'=> $ data_provider,
'export'=> false,
'columns'=> [
 ... 
],
 ... \ \  n   
 
 

但现在我想使用$ data_provider 中的相同数据,但没有分页和其他排序规范

试过这个但不起作用:

  $ data_provider-> sort = ['defaultOrder'=>  ['column_a'=> SORT_ASC,'column_b'=> SORT_DESC]] 
 $ data_provider-> pagination = false; 
   
 
 

我认为这是因为 已经使用 - &gt; search()方法检索了数据。我是否需要创建一个全新的搜索模型类?只是为了获得不同的排序? < p>提前致谢!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doutun1362 2016-08-24 09:19
    已采纳

    Before I asked the question I didn't know the dataProvider already retrieved the data on creation. So altering properties of the dataProvider doesn't do another search, it does different sorting but with the same data it already retrieved.

    Answer: I ended up making a new method in the searchModel class like this:

    public function searchByCreatedAt() {
        $query = Model::find()->orderBy(['created_at' => SORT_ASC]);
    
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => false,
        ]);
    
        ...
    }
    
    打赏 评论
  • duanao4503 2016-08-22 16:39

    You should use two dataProvider eg:

    $modelSearch = new SearchModel();
    $data_provider = $modelSearch->search(Yii::$app->request->queryParams);
    
    $data_provider2 = $data_provider;
    $data_provider2->pagination = false; 
    $data_provider2->sort = ['defaultOrder'=> ['column_a' => SORT_ASC, 'column_b' => SORT_DESC]]
    
    
     return $this->render('your_view', [
            'searchModel' => $searchModel,
            'dataProvider' => $data_provider,
            'dataProvider2' => $data_provider2,
        ]);  
    
    打赏 评论

相关推荐 更多相似问题