问题
Good morning,
I am having trouble with $hasMany, even though $hasOne works fine.
I have two models, Assignment and AssignmentGroup. Assignment can have one AssignmentGroup but AssignmentGroup can have many Assignments. Here are the relationships:
class Assignment extends AppModel {
public $belongsTo = array('AssignmentGroup');
}
class AssignmentGroup extends AppModel {
public $hasMany = array(
'Assignment' => array('foreignKey'=>'assignment_group_id),
);
}
Here's the code I'm running:
$this->AssignmentGroup->Behaviors->load('Containable');
$params = array(
'conditions' => array('AssignmentGroup.class_id' => $class_id),
'contain' => array('Assignment'),
);
$result = $this->AssignmentGroup->find('all', $params);
When I use $hasOne instead of $hasMany I get the expected result.
$result = array(
'AssignmentGroup => array(
[several elements]
),
'Assignment' => array(
[more elements]
),
);
However, when I use $hasMany, as I need to, things fall apart. The query does not have a JOIN.
$result = array(
'AssignmentGroup => array(
[several elements]
),
'Assignment' => array(),
);
Can anyone explain what's going on and/or suggest a solution? Thanks for the help.
回答1:
This might be minor, but I always make sure that I use className
in the Model definition.
var $hasMany = array(
'Assignment' => array(
'className' => 'Assignment',
'foreignKey' => 'assignment_group_id',
),
);
Just to be safe since the book does say "aliases for each model must be unique app wide" it helps me keep those straight.
Also, try using the $hasMany
but taking the contain
out just to see if that could be what's messing you up.
回答2:
class AssignmentGroup extends AppModel {
public $hasMany = array(
'Assignment' => array('foreignKey'=>'assignment_group_id),
);
}
should be:
class AssignmentGroup extends AppModel {
public $hasMany = array(
'Assignment' => array('foreignKey'=>'assignment_group_id' ),
);
}
来源:https://stackoverflow.com/questions/12114532/cakephp-success-with-hasone-failure-with-hasmany