4

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?

3 Answers 3

4

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.

2
  • 3
    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.
    Commented Jan 26, 2010 at 14:36
  • Nice approach for cases where the database is complex! For example, if you had something like User HABTM Company (with => CompaniesUser). For the case scenario of OP, a simple contain (of course with containable behavior installed) in $this->Auth->authenticate('Form' => array('contain' => array('Company', ...))). Authentication docs. EDIT: I do realize that the answer was for cake 1.2. My suggestion is for cake 2.x (that's why its a comment and not an answer!)
    – Fr0zenFyr
    Commented May 17, 2017 at 7:00
2

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.

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.