如何在 Yii2 中获取按类别排序项目的参数?

How to take get parameters for sorting items by category in Yii2?

我用的是Yii2高级模板。在我的数据库 table 中,我有带有 categry 字段的项目(从 1.. 到 inf)

控制器动作:

public function actionIndex()
{
    $searchModel = new AdsSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

查看:

<?= ListView::widget([
    'dataProvider' => $dataProvider,
    'itemOptions' => ['class' => 'item'],
    'itemView' => '_item_view',,
]) ?>

我启用了 prettyUrl

'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
        ],

和 frontend/web/

中的 .htaccess
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

1) 如何显示仅按类别找到的项目? 现在 mysite.com/items 显示所有具有混合类别的项目 我想制作 mysite.com/items/cat/1 或 mysite.com/items/1 以显示带有 category = 1

的类别

2) 有没有关于如何制作mysite.com/items/category-name-url instead number的文章?我将类别名称存储在 $app->params 中。 id = 5 的下一个项目页面将是 mysite.com/items/category-name-url/5

1) 在 urlManager 的配置中输入:

'items/cat/<id:\d+>' => '{YOUR_CONTROLLER}/{YOUR_ACTION}',

controller这样的:

public function actionIndex($id) // yii2 provide $id form url
    {                         

        $dataProvider = new ActiveDataProvider([
            'query' => AdsSearch::find()->where(['category' => $id]),
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'category' => $category
        ]);
    }

2) 在 urlManager 的配置中输入:

'items/<category>' => '{YOUR_CONTROLLER}/{YOUR_ACTION}',

controller

$subCategory = Yii::$app->request->get('category');

        $dataProvider = new ActiveDataProvider([
            'query' => AdsSearch::find()->where(['categoryUrl' => $subCategory]),
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'category' => $category
        ]);

或者在我的项目中 CategoryGoods 模型:

$category = Category::findOne(['url' => $subCategory]);

        $dataProvider = new ActiveDataProvider([
            'query' => Goods::find()->where(['categoryId' => $category->id])->with('mainPhoto'),
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'category' => $category
        ]);