简体   繁体   English

如何从cakephp中的数据库表中获取一个id值

[英]how to get a value of id from database table in cakephp

CAKEPHP CAKEPHP

I have problem to get id value from table 我从表获取ID值有问题

My table is named "users" and have id PK(int),username(txt) name(txt) 我的表名为"users"并且具有ID PK(int),username(txt) name(txt)

I have tried 我努力了

$this->users->read('users.id)

To get user id but it doesn't work. 获取用户ID,但不起作用。

I also tried 我也试过

$this->request->session()->read('users.id')

I wanna to make a condition like 我想让像

if($this->users->read('users.id'))==1 

because I wanna hide html code from users with other id. 因为我想向具有其他ID的用户隐藏html代码。 I also try use something like that ..... read('users.username')=='admin' but they wont work too 我也尝试使用类似的方法..... read('users.username')=='admin'但它们也无法正常工作

As you see a try to use session() to get id but dont work to 如您所见,尝试使用session()获取ID,但不尝试

my login function is 我的登录功能是

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {

                $this->Auth->setUser($user);
            return $this->redirect(['controller'=>'Accounts']);
        }
        $this->Flash->error('blalalalala');
    }
}

This is my first project i cakephp to school so guys can you help me? 这是我第一次上学的蛋糕,所以你们可以帮我吗? :) im weak in php :)我在php中比较弱


Thx for tips but still dont work. 谢谢技巧,但仍然无法正常工作。

i use this 我用这个

$id  =  $this->Auth->user('id');  // To get user id 
    $this->set('id', $id);

in my AppController in funciton before filter. 在过滤器之前在我的AppController中起作用。

and i use for example if($id==1) ..... and still dont work. 而且我使用例如if($id==1) .....仍然不起作用。 var dump shows null. var dump显示为空。

i forgot to say but i have CakePHP 3x version 我忘了说,但是我有CakePHP 3x version

To set user any information in controller you can use 要在控制器中为用户设置任何信息,您可以使用

$this->Auth->user('fieldName');

In AppController in beforeFilter method just set user info which you need, like as below code AppController中的beforeFilter方法中,只需设置所需的用户信息即可,如下面的代码所示

$id  =  $this->Auth->user('id');  // To get user id 
        $this->set('id', $id);   

Now in any view you can apply condition like 现在,在任何视图中,您都可以应用条件

if($id==1) 
--do this-- 

If you want to get user id anywhere you can use, It not allow in cakephp 3.x 如果您想在任何可以使用的地方获取用户ID,则在cakephp 3.x中不允许

AuthComponent::user('id')

For details you can see doc 有关详细信息,请参阅doc

you can try these: 您可以尝试以下方法:

 $this->Auth->user('id'); // for controller action

OR 要么

$this->Session->read('Auth.User.id'); // for controller and views

OR 要么

AuthComponent::user('id') // anywhere 

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

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