CakePHP 2.1.1 foreach [英] CakePHP 2.1.1 foreach
问题描述
在我看来,我想要这样的HTML表格:
In my view I want a HTML table something like this:
COUNTRY TOWN
france paris
这是我的查询:
$foo=$this->country->find('all', array(
'contain' => array(
'Town' => array(
'conditions' => array("Town.country_id = country.id"),
'fields' => array('id','name')
)
)
)
);
我想这样显示在我的视图中:
I want to display to my view like this:
line6 <?php foreach ($diponibilite as $f): ?>
line7
line8 <tr>
line9 <td><?php echo $f['country']['name'];?></td>
line10 <td><?php echo $f['town']['name'];?></td>
line11
line12 </tr>
line13 <?php endforeach; ?>
模型国家和镇相关:
country hasmany town and town belongsto country
不幸的是,出现错误:
注意(8):未定义的索引:名称[APP\View\index\index.ctp ,第10行]
Notice (8): Undefined index: name [APP\View\index\index.ctp, line 10]
为什么?
推荐答案
问题是,由于您具有 Country hasmany Town
关系,因此一个国家中可能有多个城镇(如 debug( $ f)
显示)。
The problem is that since you have a Country hasmany Town
relationship there could be multiple towns in one country (as the output of debug( $f )
shows).
要打印所有城镇,您需要另一个循环:
To print all of the towns you need another loop:
<?php foreach( $diponibilite as $f ): ?>
<tr>
<td><?php echo $f[ 'country' ][ 'name' ]; ?></td>
<td><?php
foreach( $f[ 'town' ] as $town ) {
echo $town[ 'name' ].' ';
}
?></td>
</tr>
<?php endforeach; ?>
或者,如果您只想要第一个,请使用 $ f ['镇'] [0] ['名称']
。
Or, if you just want the first one, use $f[ 'town' ][ 0 ][ 'name' ]
.
旁注:如果您已正确建立关联,则不会需要找到条件。您可以这样做
Side note: if you have the associations set up properly, you don't need the condition in the find. You can just do
$foo = $this->country->find( 'all', array(
'contain' => array(
'Town.id',
'Town.name'
)
)
);
这篇关于CakePHP 2.1.1 foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!