Question

I'm having a weird problem with my relationships/aliases in CakePHP and now its preventing me from accessing my data correctly.

I have:

  • User hasMany CreatorModule (alias for Module)
  • User HABTM LearnerModule (alias for Module)
  • Module belongsTo Creator (alias for User)
  • Module HABTM Learner (alias for User)

And I'm trying to call:

$id = $this->Module->User->findByEmail($email);
$modules = $this->Module->findByUserId($id['User']['id']);

The queries that get generated aren't correct - the table-alias is wrong. I'm not sure which of the above is responsible but I get:

SELECT
    `Creator`.`id`,
    `Creator`.`email`,
    `Creator`.`organization`,
    `Creator`.`name`,
    `Creator`.`password`,
    `Creator`.`verified`,
    `Creator`.`vcode`
FROM
    `snurpdco_cake`.`users` AS `Creator` 
WHERE
    `User`.`email` = 'foo@example.com' # <--
LIMIT 1

I figured out that the error is that CakePHP should change 'User' in the WHERE clause to Creator, but doesn't, even if I use the alias. How do I complete this query correctly.

Further, as a related problem, I find that I can no longer use User in my model calls etc now that I have defined aliases. Is there a way around this?

EDIT: As requested, here is my model code defining the aliases:

class User extends AppModel {
public $name = 'User';
public $uses = 'users';
public $hasMany = array(
    'OwnedModule' => array(
        'className' => 'Module',
        'foreignKey' => 'user_id',
        'dependent' =>  true
        ));
public $hasAndBelongsToMany = array(
    'LearnerModule' => array( 
       'className'              => 'Module',
       'joinTable'              => 'modules_users',
       'foreignKey'             => 'user_id',
       'associationForeignKey'  => 'module_id',
       'unique'                 => 'keepExisting',
    ));
//The rest of the Model
} 
//Different file, condensed here for spacing 
class Module extends AppModel {
public $name = 'Module';
public $belongsTo = array(
    'Creator' => array(
        'className' => 'User'));    
public $hasAndBelongsToMany = array(
    'Learner' => array(
       'className'              => 'User',
       'joinTable'              => 'modules_users',
       'foreignKey'             => 'module_id',
       'associationForeignKey'  => 'user_id',
       'unique'                 => 'keepExisting',
    ));
//The rest of the Model
}
Was it helpful?

Solution

try

$id = $this->Module->Creator->find('first', 
          array('conditions' => array('Creator.email' => $email)
      );
$modules = $this->Module->findByCreatorId($id['User']['id']);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top