我有点恼火,为什么第二个代码抛出异常而第一个代码不抛出异常。 self::ID_FALLBACK 为 1, 部分中有 2 行或以上 id 为 1、2... 的行;全部具有Sectiongroup_id = 1
节组中有一行 id 为 1
这没有任何问题:
public static function getSections(){
// select groups with sections
foreach(ORM::factory('Sectiongroup')->find_all() as $grp){
$s = $grp->sections->where('id', '>', self::ID_FALLBACK)->find_all()->as_array('id', 'name');
count($s) && $sections[$grp->name] = $s;
}
return $sections;
}
接下来抛出:
无法在
count($s) && $section.. 行中使用 Model_Sectiongroup 类型的对象作为数组
public static function getSections(){
// select groups with sections
$sections = ORM::factory('Sectiongroup');
foreach($sections->find_all() as $grp){
$s = $grp->sections->where('id', '>', self::ID_FALLBACK)->find_all()->as_array('id', 'name');
count($s) && $sections[$grp->name] = $s;
}
return $sections;
}
Sectiongroup 中的 2 行出现同样的错误,现在应该是一个数组:
public static function getSections(){
// select userdefined groups with sections
$sections = ORM::factory('Sectiongroup');
foreach($sections->find_all()->as_array() as $grp){
$s = $grp->sections->where('id', '>', self::ID_FALLBACK)->find_all()->as_array('id', 'name');
count($s) && $sections[$grp->name] = $s;
}
return $sections;
}
这是什么奇怪的行为?
最佳答案
在您的第一个(工作)示例中,您从未显式定义 $sections
数组,并且当您第一次编写 $sections[$grp->name] = $s
,PHP 为您创建 $sections
数组。
在最后两个示例中,您显式声明 $sections
为 ORM::factory()
的返回值,更具体地说,是 的对象子类ORM
不能使用数组下标 ([]
) 表示法。
关于php - foreach 中 kohana orm find_all() 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20203380/