Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch only some fields on find in CAKEPHP

My problem is when I fetch data of user from users table , all the fields of user table fetched from users table..but i don't want to include password and email address into that so is there any way to only fetch fields other than password and email address?

regards.

like image 405
Meet Brahmbhatt Avatar asked Dec 27 '22 11:12

Meet Brahmbhatt


2 Answers

As mentioned by juhana you don't need to use all fields that are returned by your find call. It's not clear what actual problem you're trying to solve and it would be in your interest to clarify such details in future questions.

For direct queries

For queries directly on your user model you can use some logic like this:

public function beforeFind($queryData) {
    if (empty($queryData['fields'])) {
        $schema = $this->schema();
        unset($schema['password']);
        unset($schema['email']);

        foreach (array_keys($schema) as $field) {
            $queryData['fields'][] = $this->alias . '.' . $field;
        }
        return $queryData;
    }

    return parent::beforeFind($queryData);

}

However

This won't do anything for queries where you query another model e.g.

$results = $PostModel->find('all', array(
    'contain' => array('User')
));

In the above case, all user fields will be returned. For uses like this it's probably best to define your field list explicitly rather than rely on any automatic magic:

$results = $PostModel->find('all', array(
    'contain' => array('User')
    'fields' => array('Post.*', 'User.name')
));
like image 115
AD7six Avatar answered Jan 15 '23 01:01

AD7six


you have to do something like this

$this->Model->find('all',array('fields'=>array('id','name')));     

Just mention your require fields on fields array.

if you want to fetch from model then try this

$this->find('all',array('fields'=>array('id','name')));     

Thanks.

like image 31
Moyed Ansari Avatar answered Jan 15 '23 02:01

Moyed Ansari