ahjohnston25
ahjohnston25

Reputation: 1975

CakePHP: Call to a member function on a non-object error with aliases

I keep getting a "Call to a member function on a non-object" error in the index function of one of my controllers. Here is the code:

class ModulesController extends AppController {
     public $uses = array('Module', 'User');
     public $scaffold;
     function index() {
     if ($this->request->is('get')) { //Technically unecessary but good practice
       $email = AuthComponent::user('email'); 
       $user = $this->Module->User->findByEmail($email);
      //Code omitted
     }
}

And this is my Module model:

class Module extends AppModel {
public $name = 'Module';
public $hasMany = array(
    'Slide' => array(
        'className'  => 'Slide',
        'foreignKey' => 'module_id',
        'order' => 'Slide.position ASC' //Let's make sure that name is correct
        ));
public $belongsTo = array(
    'Creator' => array(
        'className' => 'User'));    
public $hasAndBelongsToMany = array(
    'OUser' => array(
       'className'              => 'User',
       'joinTable'              => 'modules_users',
       'foreignKey'             => 'module_id',
       'associationForeignKey'  => 'user_id',
       'unique'                 => 'keepExisting',
    ));
       } //Unnecessary code omitted 

And this is the code for my user model:

class User extends AppModel {
public $name = 'User';
public $uses = 'users';
public $hasMany = array(
    'OModule' => array( //Owner of Modules
        'className' => 'Module',
        'foreignKey' => 'user_id',
        'order' => 'Module.created DESC'
        ));
public $hasAndBelongsToMany = array(
    'Module' => array(
       'className'              => 'Module',
               'joinTable'              => 'modules_users',
               'foreignKey'             => 'user_id',
               'associationForeignKey'  => 'module_id',
               'unique'                 => 'keepExisting',
    ));
} //Unnecessary code omitted    

It is worth mentioning that User and Module have both a belongsTo and a HABTM relationship, so User has the aliases Creator and OUser respectively. In the code above, the findByEmail is trying to use the Creator relationship, but that gives me the same error.

My question is, how do I call the findByEmail() method without error?

Upvotes: 1

Views: 3141

Answers (1)

Dave
Dave

Reputation: 29121

Change:

$user = $this->Module->User->findByEmail($email);

To:

$user = $this->User->findByEmail($email);

Voila!

Reason:

Somehow, there is either 1) no relationship between Module and User, 2) a mistake in the relationship, or 3) your using an alias for either or both of them so that using Module->User wouldn't be correct.

You're loading the 'User' model anyway though, so there's no reason to go through the Module model to access it - just access it directly (like example above).

Upvotes: 2

Related Questions