修改beforeFind回调中需要的可容纳字段? [英] Modifying Containable fields required in beforeFind callback?

查看:128
本文介绍了修改beforeFind回调中需要的可容纳字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的CakePHP 1.2.5应用程序中,我有一个配置文件模型,属于一个用户模型。 User模型有一个 username 字段,当在Profile模型上执行 find()时,我想始终自动检索 User.username 的值。我认为修改我的Profile模型的 beforeFind()方法可以自动包含所需的字段。

In my CakePHP 1.2.5 app, I have a Profile model that belongsTo a User model. The User model has a username field, and when performing a find() on the Profile model, I want to always automatically retrieve the value of User.username too. I figure it would make sense to modify my Profile model's beforeFind() method to automatically contain the desired field.

这是我试图做的:

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'] 正在更新,但用户名数据未检索。我查看了CakePHP核心代码的 find()方法,我发现 beforeFind()回调是在所有Behaviors的回调之后被调用,这意味着Containable在我能够修改它之前就已经做了它所需要处理的 $ queryData ['contains'] 的值。

I can see that the value of $queryData['contain'] is properly being updated, but the username data isn't being retrieved. I looked into the CakePHP core code for the find() method, and I found that the beforeFind() callback is being called after all Behaviors' callbacks, meaning that Containable already did what it needed to do with the value of $queryData['contain'] before I was able to modify it.

如何解决这个问题而不需要破解核心?

How can I work around this without hacking the core?

推荐答案

我解决了,所以这里是我的答案,如果任何人有相同的复杂性。由于所有行为的 beforeFind()方法被称为先于到模型的 beforeFind(),所以不能在beforeFind中指定可容纳字段。 方法。

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.

因此,我需要修改 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);
}

这篇关于修改beforeFind回调中需要的可容纳字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆