CakePHP 2.x:Model :: afterFind()上的$primary标志是否真的有
Cake
PHP的Model :: afterFind()回调如下所示:
afterFind(array $results,boolean $primary = false) 根据文件:
他们可以有所不同,但实验表明它们并不总是有差异.据我所知,$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; } 这是黑客,我不喜欢它,但它似乎比$primary更有用. 明确指出,我的问题是: > $主标记实际有用的是什么?
事实上,$primary参数似乎只能在警告您的$结果的格式是不可预测的情况下有用.在确定$结果的格式方面无效.
更多信息: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数组的开销. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |