CakePHP 2.1.1 foreach

有些话、适合烂在心里 提交于 2020-01-06 07:31:10

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/10342755/cakephp-2-1-1-foreach

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!