CakePHP 2.1.1 foreach

In my view I want a HTML table something like this:

COUNTRY TOWN france paris

This is my query:

$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; ?>

The models 'country' and 'town' are associated:

country hasmany town and town belongsto country

unfortunately, an error:

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

Why?

Answer1:

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; ?>

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

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:CakePHP 2.1.1 foreach