如何在Cakephp中的扩展模型中继承AppModel的$ belongsTo

时间:2014-06-23 10:20:28

标签: cakephp inheritance model associations

在Cakephp中 我在AppModel中使用了belongsTo

class AppModel extends Model {
    public $actsAs = array('Containable');

    public $belongsTo = array(
        'ModifiedBy' => array(
            'className' => 'User',
            'foreignKey' => 'common_modified_by_user_id'
        )
    ); 
}

现在我也想在UserModel中应用属于

class User extends AppModel {

    public $belongsTo = array(
        'School' => array(
            'className' => 'User',
            'foreignKey' => 'school_id'
        )
    );

}

但是当我这样做的时候......它超越了app模型的belongsTo,并且学校数据来自于获取的数组....

请帮助......

1 个答案:

答案 0 :(得分:2)

没有自动合并关联

除了$actsAs$findMethods变量之外,关联配置不会自动合并,您必须自己合并。

解决起来应该相当简单,在Object::_mergeVars()模型中使用User构造函数应该可以解决这个问题:

public function __construct($id = false, $table = null, $ds = null) {
    $parent = get_parent_class($this);
    $this->_mergeVars(array('belongsTo'), $parent);

    parent::__construct($id, $table, $ds);
}

PS。您可能希望查看behaviors,它们可能是满足您需求的更好选择。