1

我有一个模型,我想检查更多插件,如果加载了插件,则将插件中的模型附加到 man 模型中。我用这个方法?但不同的结果导致模型和行动。是另一种比构造更好的方法来绑定更多插件检查。

class Comment extends AppModel {

/**
 * @see Model::$belongsTo
 */
    public $belongsTo = array(
        'Content' => array(
            'className' => 'Content',
            'foreignKey' => 'object_id',
            'conditions' => array(
                'Comment.object_id = Content.id',
            )
        ),
    );

/**
 * @see Model::__construct
 */
    public function __construct($id = false, $table = null, $ds = null) {
        // parent
        parent::__construct($id, $table, $ds);

        // check for newsstudio
        if (CakePlugin::loaded('NewModel')) {
             $this->bindModel(
                array('belongsTo' => array(
                    'NewModel' => array(
                        'className' => 'NewModel.NewModel',
                        'foreignKey' => 'object_id',
                        'conditions' => array(
                            'Comment.object_id = NewModel.id',
                        )
                    )
                )
            ));
        }

        var_dump($this->belongsTo); // correct! NewModel added to blongsto
    }
}

// but in action during use. Plugin loaded but 
var_dump($this->Comment->belongsTo); // incorrect! just `Content` added
4

1 回答 1

0

考虑到您在 __construct 中执行此操作,您不妨$belongsTo在调用父级之前将其添加到属性中,这将节省一些 CPU 周期,因为您没有执行额外的方法调用。

class Comment extends AppModel {

/**
 * @see Model::$belongsTo
 */
    public $belongsTo = array(
        'Content' => array(
            'className' => 'Content',
            'foreignKey' => 'object_id',
            'conditions' => array(
                'Comment.object_id = Content.id',
            )
        ),
    );

/**
 * @see Model::__construct
 */
    public function __construct($id = false, $table = null, $ds = null) {
        // check for newsstudio
        if (CakePlugin::loaded('NewModel')) {
            $this->belongsTo['NewModel'] = array(
                        'className' => 'NewModel.NewModel',
                        'foreignKey' => 'object_id',
                        'conditions' => array(
                            'Comment.object_id = NewModel.id',
                        )
                    );
        }
        parent::__construct($id, $table, $ds);
    }
}
于 2012-07-05T12:00:28.997 回答