我在表单上有<select>
的以下代码。
$query = $em->createQuery("SELECT g.name, g.id FROM SSMURBS\Group g ORDER BY g.name ASC");`
$groups = $query->iterate();`
$groups_option = "";
foreach( $groups as $row ){
$group = $row[0];
$groups_option .= "<option val=\"{$group['id']}\">{$group['name']}</option>\n";
}
但这会引发错误。有效的是......
$query = $em->createQuery("SELECT g.name, g.id FROM SSMURBS\Group g ORDER BY g.name ASC");
$groups = $query->iterate();
$groups_option = "";
$i = 0;
foreach( $groups as $row ){
$group = $row[$i];
$groups_option .= "<option val=\"{$group['id']}\">{$group['name']}</option>\n";
$i++;
}
我做错了吗?参考手册引用第一个选项为正确...
答案 0 :(得分:1)
我找到了自己问题的答案:
虽然DQL允许SELECT g.id, g.name
而不会抛出错误,但这实际上是SQL,而不是DQL。 (谢谢,学说参考手册,因为这个很清楚...)
正确的编码方式是
$query = $em->createQuery("SELECT partial g.{id,name} FROM SSMURBS\Group g ORDER BY g.name ASC");
$groups = $query->iterate();
$groups_option = "";
foreach( $groups as $group ){
$group = $group[0];
$groups_option .= "<option value=\"{$group->id}\">{$group->name}</option>\n";
}
答案 1 :(得分:0)
您的变量名称不匹配。
删除$group = $row[0]
并使用foreach ($groups as $group)
$query = $em->createQuery("SELECT g.name, g.id FROM SSMURBS\Group g ORDER BY g.name ASC");
$groups = $query->iterate();
$groups_option = "";
foreach ( $groups as $group ){
$groups_option .= "<option val=\"{$group['id']}\">{$group['name']}</option>\n";
}