簡體   English   中英

如何在URL中添加用戶名而不是cakephp 3中的user_id

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

我希望我的網址像這樣的格式http:// localhost / blog / users / username而不是這個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']);
}

我嘗試了此鏈接,但沒有解決我的問題

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

}

在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 )是有原因的嗎? 您應該只從中獲得一個用戶,對嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM