如何在 cakephp 3 中将用户名附加到 url 而不是 user_id

how to append the username in url instead of user_id in cakephp 3

我想要我的url这样的格式http://localhost/blog/users/username instead of this http://localhost/blog/users/view/6

我在用户视图中有此代码index.ctp

<?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']);
}

}

In 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
}

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

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

还有,你这里的变量是复数($users)有什么原因吗?您应该只能从中获得一个用户,对吧?