【问题标题】:Sort mixed models with one dataprovider using ArrayDataProvider使用 ArrayDataProvider 对具有一个数据提供者的混合模型进行排序
【发布时间】:2017-11-19 09:50:01
【问题描述】:

我使用ArrayDataProvider 混合模型,然后将它们合并到一个数据提供者中。我在网格视图中使用了数据提供程序,一切正常。 但是我需要按一列排序网格视图我尝试了很多解决方案,但都没有奏效。

这是我的型号代码(按 item_order 排序)

public function getAllSelectedItemsInTheUnit($unitId, $grid = false)
    {
        $finalList = array();
        $storiesList = array();
        $activityList = array();
        $breakList = array();
        $stories = UnitStories::find()->joinWith(['story'])->where("unit_id=$unitId")->all();
        if (count($stories) > 0) {
            foreach ($stories as $item) {
                $storiesList[] = [
                    'key' => self::TYPE_STORY . $item->id,
                    'id' => $item->id,
                    'title' => $item->story->title,
                    'type' => self::TYPE_STORY,
                    'item_order' => $item->unit_order,
                ];
            }
        }

        $activities = UnitActivities::find()->joinWith(['activity'])->where("unit_id=$unitId")->all();
        if (count($activities) > 0) {
            foreach ($activities as $item) {
                $activityList[] = [
                    'key' => self::TYPE_ACTIVITY . $item->id,
                    'id' => $item->id,
                    'title' => $item->activity->title,
                    'type' => self::TYPE_ACTIVITY,
                    'item_order' => $item->activity_order,
                ];
            }
        }

        $breaks = UnitBreaks::find()->where("unit_id=$unitId")->all();
        if (count($breaks) > 0) {
            foreach ($breaks as $item) {
                $breakList[] = [
                    'key' => self::TYPE_BREAK . $item->id,
                    'id' => $item->id,
                    'title' => $item->title,
                    'type' => self::TYPE_BREAK,
                    'item_order' => $item->unit_order,
                ];
            }
        }
         $finalList = array_merge($storiesList, $activityList, $breakList);
         $dataProvider = new ArrayDataProvider([
                'allModels' => $finalList, 'key' => 'key',
                'sort' => [
                    'attributes' => ['item_order'],
                ],

            ]);

            return $dataProvider;


    }

任何解决方案都会非常好,即使通过纯 PHP 对数组进行排序,我想都可以解决问题。

【问题讨论】:

    标签: php arrays activerecord yii yii2


    【解决方案1】:

    您可以使用usort()

    usort($finalList, function ($a, $b) {
        return $a['item_order'] < $b['item_order'];
    });
    

    在回调&gt;, &lt;, &lt;= 等中添加您的条件

    【讨论】:

      猜你喜欢
      • 2011-12-18
      • 2021-02-10
      • 2020-06-11
      • 2013-08-22
      • 2018-10-17
      • 2014-06-22
      • 2021-02-15
      • 2023-03-14
      • 2012-11-07
      相关资源
      最近更新 更多