CakePHP - success with $hasOne, failure with $hasMany

a 夏天 提交于 2019-12-12 21:43:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!