【问题标题】:Pass findBy parameter to callback method afterFind将 findBy 参数传递给回调方法 afterFind
【发布时间】:2012-09-24 06:28:13
【问题描述】:

我正在尝试捕获某个 findBy 调用(使用 afterFind),其中:

如果$results为空(或者你要查找的值不存在),但是在另一个表上找到了参数值,那么它会修改$results为有效

一些控制器操作得到了这个:

$this->User->findByUsername("Bingo"); // yes, username Bingo doesnt exist on users table

用户模型:

function afterFind($results, $primary){
    if(empty($results)) {
        if(in_array($findbyparameter, array("Bingo", "Bingo1", "Bingo2"))) {
            // modify $results
        }
    }
}

问题是,我如何获得$findbyparameter?

谢谢!我们将不胜感激所有帮助!

【问题讨论】:

标签: php cakephp cakephp-model


【解决方案1】:

我没有使用这些方便的方法,但您可以像这样将变量作为模型属性传递:

//where you search 
$this->User->searchPhrase = "Bingo";
findByUsername($this->User->searchPhrase);

//Model
function afterFind($results, $primary){
    if(empty($results)) {
        if(in_array($this->searchPhrase, array("Bingo", "Bingo1", "Bingo2"))) {
            // modify $results
        }
    }
}

这不是最漂亮的方法,但我想它会起作用。尝试在 afterFind 方法中 print_r($this) 看看你是否可以在某个地方找到你搜索的短语。我相信它是在条件数组中传递的。

【讨论】:

  • 谢谢。我会用这个代替。在 afterFind 上尝试了 var_dump($this) 并发现 read() 传递了参数但没有找到(并且 findBy 有效)
【解决方案2】:

也许您正在寻找自定义查找类型。自定义查找类型有两种状态:beforeafter

在您设置条件之前,在之后您将检查您的数据并在必要时进行修改。在这两个州,您都可以访问查询选项。

在 1.x 和 2.x 中设置自定义查找略有不同(您没有提到您使用的是哪个版本),因此您可以在书中查找具体内容。

简而言之,您可以将您的查找类型添加到模型的$findMethods 属性中,然后将相应的方法名称添加到您的模型中。假设您将自定义查找类型称为“byUsername”

protected function _findByUsername($state, $query, $results = array()) {
    if ($state === 'before') {
        // add your condition to the query, 
        return $query;
    } elseif ($state === 'after') {
        // modify $results if you need to
        return $results;
    }
}

你可以通过$this->User->find('byUsername', array('username' => $username));调用它

$query 中,您将拥有“用户名”键,您可以将其添加到$queryconditions 键中。在这两个州,您都可以访问$query['username']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 2020-07-03
    相关资源
    最近更新 更多