droc60607 2018-01-22 05:21
浏览 49
已采纳

如何在url中添加用户名而不是cakephp 3中的user_id

I want my url like this format http://localhost/blog/users/username instead of this http://localhost/blog/users/view/6

I have this code in Users view index.ctp

enter image description here

<?php foreach ($users as $user): ?>
<?= $this->Html->link(__('View Profile'), ['action' => 'view', $user['user']['slug']]) ?>
<?php endforeach; ?>

routes.php

<?php
 $routes->connect('/user/*', array('controller' => 'users', 'action' => 'view'));
?>


//public function view($id = null)
public function view($username)
{

    $users = $this->Users->get($username, [
        'contain' => ['Subjects'] // i have relation
    ]);
    $this->set('users', $users);
    $this->set('_serialize', ['user']);
}

I tried this link but it not solved my problem

public function edit($id = null)
{
  //$logged_user_id=$this->request->Session()->read('Auth.user.id');


  $logged_user_id=$this->Auth->user('id');
  if($logged_user_id==$id){
      $user = $this->Users->get($id, [
        'contain' => []
    ]);
      if ($this->request->is(['patch', 'post', 'put'])) {
        $user = $this->Users->patchEntity($user, $this->request->getData());


        if ($this->Users->save($user)) {
            $this->Flash->success(__('User profile successfuly  updated.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }

    }
    $this->set(compact('user'));
    $this->set('_serialize', ['user']);
} else {
    $this->Flash->error(__('You are not allowed to do this.'));
    return $this->redirect(['action' => 'index']);
}

}

  • 写回答

2条回答 默认 最新

  • doushan1850 2018-01-22 09:07
    关注

    In index.ctp

    <?php foreach ($users as $user): ?>
    <?= $this->Html->link(__('View Profile'), ['action' => 'view', $user->username]) ?>
    <?php endforeach; ?>
    

    Please change $user->username as per your structure.

    You don't have to do anything in your routs.php

    the username will receive as an argument of the function view

    function view($username){
        //Your code
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛