我希望我的网址格式为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']);
}
我试过这个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']);
}
}
答案 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
)?你应该只从这个中获得一个用户,对吗?