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

时间:2018-01-22 05:21:33

标签: php css cakephp cakephp-3.0

我希望我的网址格式为http://localhost/blog/users/username,而不是此http://localhost/blog/users/view/6

我在用户视图中有这个代码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']);
}

我试过这个link,但它没有解决我的问题

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 个答案:

答案 0 :(得分:2)

  

在index.ctp

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

请根据您的结构更改$user->username

您无需在 routs.php

中执行任何操作

用户名将作为函数视图的参数

接收
function view($username){
    //Your code
}

答案 1 :(得分:1)

get函数使用模型的主键字段。可能会将主键更改为username,但我怀疑这会导致其他问题。相反,试试这个:

$users = $this->Users->find('first')
    ->where(['username' => $username])
    ->contain(['Subjects']);

此外,您的变量是否为复数($users)?你应该只从这个中获得一个用户,对吗?

相关问题