gpt4 book ai didi

CakePHP 2.x:Model::afterFind() 上的 $primary 标志真的有用吗?

转载 作者:行者123 更新时间:2023-12-03 21:30:16 26 4
gpt4 key购买 nike

CakePHP 的 Model::afterFind()回调看起来像:

afterFind(array $results, boolean $primary = false)

根据文档:

The $primary parameter indicates whether or not the current model was the model that the query originated on or whether or not this model was queried as an association. If a model is queried as an association the format of $results can differ.



它们可以不同,但​​实验表明它们并不总是不同的。据我所知, $primary参数实际上并不是那么有用。如果设置为 false您可能会或可能不会获得扁平化的数据结构,因此您可能会或可能不会收到可怕的“无法将字符串偏移用作数组”错误消息。

虽然我还没有尝试过,但我基于文档的想法是忽略 $primary完全标记并检查数据:
public function afterFind($results, $primary = false) {
if (array_key_exists(0, $results) {
// operate on $results[0]['User']['fieldname']
} else {
// operate on $results['fieldname']
}
return $results;
}

这是hackish,我不喜欢它,但它似乎比 $primary 更有用。 .

明确地说,我的问题是:
  • 什么是$primary flag实际上有什么用?
  • 我是否正确,它对于确定 $results 的结构没有用?阵列,还是我错过了什么?
  • 最佳答案

    确实是$primary参数似乎只在警告您 $results 格式的情况下有用。是不可预测的。在确定 $results 的格式时没有用.

    更多信息在这里:https://groups.google.com/forum/?fromgroups=#!topic/cake-php/Mqufi67UoFo

    那里提供的解决方案是检查 !isset($results[$this->primaryKey])看看是什么格式$results是。这也是一个小技巧,但可以说比检查键 '0' 更好。

    我最终想出的解决方案是做这样的事情:

    public function afterFind($results, $useless) {

    // check for the primaryKey field
    if(!isset($results[$this->primaryKey])) {
    // standard format, use the array directly
    $resultsArray =& $results;
    } else {
    // stupid format, create a dummy array
    $resultsArray = array(array());
    // and push a reference to the single value into our array
    $resultsArray[0][$this->alias] =& $results;
    }

    // iterate through $resultsArray
    foreach($resultsArray as &$result) {
    // operate on $result[$this->alias]['fieldname']
    // one piece of code for both cases. yay!
    }

    // return $results in whichever format it came in
    // as but with the values modified by reference
    return parent::afterFind($results, $useless);
    }

    这减少了代码重复,因为您不必两次编写字段更改逻辑(一次用于数组,一次用于非数组)。

    您可以通过返回 $resultsArray 来完全避免引用内容。在方法的末尾,但我不确定如果 CakePHP(或其他一些父类)期望 $results 可能会导致什么问题以它传入的方式。另外,这种方式没有复制 $results 的开销。大批。

    关于CakePHP 2.x:Model::afterFind() 上的 $primary 标志真的有用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14106283/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com