简体   繁体   English

使用cakephp更新表字段时出错

[英]error updating table field with cakephp

i have a controller in cakephp named AdminsController. 我在cakephp中有一个名为AdminsController的控制器。 With the addadmin($id) function,as you can see,i try to update a user's role to 'admin',finding him in the database using his user id (the variable $id). 使用addadmin($ id)函数,如您所见,我尝试将用户的角色更新为“admin”,使用他的用户ID(变量$ id)在数据库中找到他。

class AdminsController extends AppController {

public $helpers = array('Html','Form');
var $uses = array('Admin', 'User');



public function index() {
    if(!($this->Auth->user('username') && $this->Auth->user('role') == 'admin')) {
        throw new NotFoundException(__('Unauthorized access.Please login first.'));
        $this->redirect(array('controller' => 'users','action' => 'login'));

    }
}



public function addAdmin($id) {
    $this->loadModel('User');
    $this->User->id = $id;
    $this->User->set('role','admin');
    $this->User->save();
}



}

But this code does not work,though many other cakephp users in stackoverflow have told me that this is the way to do this.. Do you knwo what maybe goes wrong or you can help me in any case? 但是这个代码不起作用,虽然stackoverflow中的许多其他cakephp用户告诉我这是这样做的方法..你知道可能出错的地方或者你可以帮助我吗?

thank you in advance! 先感谢您!

Try this: 尝试这个:

public function addAdmin($id) {
    $this->loadModel('User');
    $this->User->id = $id;
    $this->User->saveField('role','admin');
}

If that doesn't work, you are not getting the right ID. 如果这不起作用,则表示您没有获得正确的ID。

Is 'role' is a field in your users table? “角色”是您的users表中的字段吗? And is 'admin' a valid value for that field? 并且'admin'是该字段的有效值吗? If so this should work: 如果是这样,这应该工作:

$this->User->id = $id;
$this->User->saveField('role', 'admin');

See here . 看到这里 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM