Fetch only some fields on find in CAKEPHP

Meet Brahmbhatt picture Meet Brahmbhatt · Jan 9, 2013 · Viewed 24k times · Source

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.

Answer

AD7six picture AD7six · Jan 9, 2013

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