views:

251

answers:

3

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?

+1  A: 

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.

Funky Dude
+2  A: 

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.

jpdelatorre
It would probably be more convenient if you wrote to the `Auth.User.Company` session key. This will allow you to use the AuthComponent wrapper methods for accessing session values: `$this->Auth->user('Company.field');`
deizel
+1  A: 

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.

Leo