Modifying Containable fields required in beforeFind callback?

余生颓废 提交于 2019-12-03 20:25:25

I solved it, so here's my answer in case anyone has the same complication. Containable fields cannot be specified in beforeFind since all Behaviors' beforeFind() methods are called prior to the model's beforeFind() method.

As such, it was necessary for me to modify the find() method directly on the Profile model in order to append my custom containable field.

public function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
    $this->contain("{$this->User->alias}.{$this->User->displayField}");
    return parent::find($conditions, $fields, $order, $recursive);
}

Matt, I believe it's a nice solution. I'm using CakePHP 2.0.4 and I was intending to fetch only User model data.

Just for the record, setting actsAs for User model

class User extends AppModel {
    public $name = 'User';
    public $belongsTo = array('Role');
    public $actsAs = array('Containable');
    ...

Then I override the find method this way:

public function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
    $this->contain();
    return parent::find($conditions, $fields, $order, $recursive);
}

Or, if intending to fetch Profile data, for example:

public function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
    $this->contain(array('Profile'));
    return parent::find($conditions, $fields, $order, $recursive);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!