加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 修改beforeFind回调中所需的可包含字段?

发布时间:2020-12-13 21:35:24 所属栏目:PHP教程 来源:网络整理
导读:在我的Cake PHP 1.2.5应用程序中,我有一个属于用户模型的Profile模型. User模型有一个用户名字段,当在Profile模型上执行find()时,我想总是自动检索User.username的值.我认为修改我的Profile模型的beforeFind()方法以自动包含所需的字段是有意义的. 这是我试
在我的Cake PHP 1.2.5应用程序中,我有一个属于用户模型的Profile模型. User模型有一个用户名字段,当在Profile模型上执行find()时,我想总是自动检索User.username的值.我认为修改我的Profile模型的beforeFind()方法以自动包含所需的字段是有意义的.

这是我试图做的事情:

public function beforeFind($queryData) {
    // determine if the username data was already requested to be included in the return data via 'User.username' or 'User' => array('username').
    $hasUserData  = isset($queryData['contain']) && in_array("User.{$this->User->displayField}",$queryData['contain']);
    $hasUserData |= isset($queryData['contain']['User']) && in_array($this->User->displayField,$queryData['contain']['User']);

    // request the the username data be included if it hasn't already been requested by the calling method
    if (!$hasUserData) {
        $queryData['contain']['User'][] = $this->User->displayField;
    }

    return $queryData;
}

我可以看到$queryData [‘contains’]的值正在被正确更新,但是没有检索到用户名数据.我查看了find()方法的CakePHP核心代码,我发现在所有Behaviors的回调之后调用了beforeFind()回调,这意味着Containable已经完成了对$queryData [‘的值所做的事情.在我能够修改之前包含’].

如何在不破解核心的情况下解决这个问题?

解决方法

我解决了,所以这是我的答案,以防任何人有同样的复杂情况.无法在beforeFind中指定可包含的字段,因为在模型的beforeFind()方法之前调用所有Behaviors的beforeFind()方法.

因此,我有必要直接在Profile模型上修改find??()方法,以便附加我的自定义可包含字段.

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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读