CakePHP - success with $hasOne, failure with $hasM

2019-07-16 04:52发布

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.

2条回答
家丑人穷心不美
2楼-- · 2019-07-16 05:02
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' ),
);
}
查看更多
时光不老,我们不散
3楼-- · 2019-07-16 05:14

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.

查看更多
登录 后发表回答