doumei9589 2014-03-08 12:57
浏览 74
已采纳

Yii如何在模型中使用Id呈现用户页面,但在URL中使用用户名而不是ID

I have Users pages. In index view they all have hyperlinks on ID, and so they are sending ID to model. And when u press the link the users View is loaded and the url becomes

/site/users/1

But what I want is the URL to be not users ID but users Username like

/site/users/Alex

How can I do it ? This is my _view

<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>

Controller

public function actionView($id)
{
    $this->render('view',array(
        'model'=>$this->loadModel($id),
    ));
}
  • 写回答

1条回答 默认 最新

  • duanbo6482 2014-03-08 14:04
    关注

    You will need to modify the following files :-

    main.php(config)

    "urlManager" => array(
        "rules" => array(
            "/site/users/<name:[\w\_]>" => "/site/users/view",
            //All the other rules here...
        )
    )
    

    Controller

    public function actionView($name){
        $mdoel = User::model()->findByAttributes(array(
            "username" => $name
        ));
        if($model){
            $this->render("view", array(
                "model" => $model
            ));
        }
    }
    

    And wherever you are putting a link, make the link as follows :-

    <?php echo CHtml::link(CHtml::encode($data->id), array("view", "name" => $data->username)); ?>
    

    Update :-

    Try using the following syntax :-

    <?php echo Chtml::link(CHtml::encode($data->id), $this->createUrl('view', array('name'=>$model->username))); ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大