Rytis
Rytis

Reputation: 1445

CakePHP Auth retrieve extra data

I am just learning CakePHP, so excuse me

I am using CakePHP 1.2.5 Auth component with UsersController. User model contains two tables:

class User extends AppModel {
    var $name = 'User';
    var $belongsTo = 'Company';
}

When login() is called, I see the data being retrieved in the SQL log (LEFT JOIN is being executed), so the model seems correct, but Auth only stores the data from users table and drops everything else. How can I retrieve company data later on without doing an extra query?

Upvotes: 4

Views: 3378

Answers (3)

Leo
Leo

Reputation: 6571

Better than altering the core, try containable behaviour: http://book.cakephp.org/view/474/Containable . There is a user/profile/ example near the bottom of the page.

Upvotes: 1

jpdelatorre
jpdelatorre

Reputation: 3593

Or if you're not comfortable modifying core library like me, you could also do...

on your UsersController.login action

function login() {
    if ($this->Auth->user()) {
        $Session->write('Company', $this->User->Company->findById($this->Auth->user('id')));
        $this->redirect($this->Auth->redirect());
    }

}

You can access company details using $this->Session->read('Company.name') on your controller and $session->read('Company.name') on your views. Don't forget to add Session component and helper.

Upvotes: 4

Funky Dude
Funky Dude

Reputation: 3947

in cake/libs/controller/components/auth.php on line 819, it should be

$data = $model->find(array_merge($find, $conditions), null, null, 0);

try changing it to

$data = $model->find(array_merge($find, $conditions), null, null, 1);

basically set recursive to 1 might need to do this at some other places too.

Upvotes: 2

Related Questions