yii2如何从表格

时间:2017-02-25 13:51:34

标签: php yii yii2 yii2-advanced-app yii2-model

我创建了一个动态导航栏菜单,但无法通过参数获取正确的网址。

这是我的模型代码的一部分:

public function getNavMenu($menu_id)
{
    $menu = Menus::find($menu_id)
        ->where('menu_id = :menu_id', [':menu_id' => $menu_id])
        ->orderBy('order')
        ->all();

    // $data=[];

    foreach ($menu as $menus) {

        if (isset($menus->parent)) {

            $submenu[$menus->id] = [
                'label'   => Yii::t('frontend', ($menus['name'])),
                'url'     => parse_url($menus['route']),
                'options' => [
                    ['class' => 'nav nav-pills nav-stacked'],
                    ['class' => 'nav nav-second-level'],
                    ['class' => 'nav nav-third-level'],
                ],
            ];

            $data[$menus->parent]['items'] = $submenu;

        } else {

            # menu
            $data[$menus->id] = [
                'label' => Yii::t('frontend', ($menus['name'])),
                'url'   => (substr($menus["route"], 0, 4) == "http")
                    ? $menus["route"]
                    : [$menus["route"]],
            ];
        }

    }

    return $data;
}

我的页面操作:

public function actionView($slug)
{
    $this->layout = '@frontend/views/layouts/original/main.php';
    $model = Page::find()->where(['slug'=>$slug, 'status'=>Page::STATUS_PUBLISHED])->one();
    if (!$model) {
        throw new NotFoundHttpException(Yii::t('frontend', 'Page not found'));
    }

    $viewFile = $model->view ?: 'view';
    return $this->render($viewFile, ['model'=>$model]);
}

我的静态路线是:['label' => Yii::t('frontend', 'About'), 'url' => ['/page/view', 'slug'=>'about']]

如果我通过以下方式之一在列链接中插入记录:

  • /page/view, slug=>about
  • /page/about

网址会显示:http://yii2-web.dev/page/view,slug=abouthttp://yii2-web.dev/page/about,肯定无法找到结果。

1 个答案:

答案 0 :(得分:0)

您应该使用yii2提供的路由功能,而不是构建自定义路由,例如:Url :: to(...)

假设值'关于'在$ menu [' route']内,您的控制器位于命名的'页面'您在命名' actionView'中的行动你shluld

use yii\helpers\Url;

// Url::to() calls UrlManager::createUrl() to create a URL
 $data[$menus->id]= ['label' => Yii::t('frontend', ($menus['name'])),
                       'url'=> Url::to(['/page/view', 'slug'=>$menus['route']])
              ];

尝试深入了解:

http://www.yiiframework.com/doc-2.0/guide-runtime-routing.html

http://www.yiiframework.com/doc-2.0/guide-helper-url.html