2012-04-26 55 views
0

在我看来,我希望有一个HTML表是这样的:CakePHP的2.1.1的foreach

 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') 
      ) 
     ) 
    ) 
); 

我要显示我的看法是这样的:

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 

不幸的是,一个错误:

Notice (8): Undefined index: name [APP\View\index\index.ctp, line 10]

为什么?

+0

让我们从基本的调试开始吧。将'debug($ f);'添加到循环内部的视图中。它有'name'键吗? – JJJ 2012-04-27 06:40:28

+0

嗨Juhana!谢谢你的评论。我做了你的建议:加调试($ F)的循环内的观点,这是内容:“阵列( \t '国家'=>阵列( \t \t '身份证'=> '1', \t \t '名称'=> '法国' \t) \t '镇'=>数组( \t \t(INT)0 =>数组( \t \t \t 'ID'=> '1', \t \t \t“ name'=>'paris', \t \t \t 'COUNTRY_ID'=> '1' \t \t) \t \t(INT)1 =>数组( \t \t \t 'ID'=> '2', \t \t \t '名称'=> '马赛' , \t \t \t 'COUNTRY_ID'=> '1' \t \t) \t) )”我得到同样的错误。我想我不使用正确的语法来查找foreach()的数组中的值????谢谢! – John 2012-04-27 08:29:36

回答

2

问题是,由于你有一个Country hasmany Town关系,可能在一个国家有多个城镇(如debug($f)的输出所示)。

要打印的所有城镇,你需要另一个循环:

<?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[ 'town' ][ 0 ][ 'name' ]

备注:如果您已正确设置关联,则不需要查找中的条件。你可以做

$foo = $this->country->find('all', array(
    'contain' => array(
      'Town.id', 
      'Town.name' 
     ) 
    ) 
); 
+0

非常感谢Juhana!按照你的建议,我的错误消失了!这是我的代码:
'

' ' \t​​国家 \t \t​​镇' '?' ' '' '​​<?php echo $ f ['country'] ['name']; ?>'' ​​'' '' ' '<?php endforeach; ?>'' '
和视图显示是这样的: 乡村小镇 法国巴黎 法国马赛 再次感谢Juhana! – John 2012-04-27 10:47:39