问题描述:

I added this line in my controller :

public $uses = array('DemandeFormation','Formation');

i read it will allow me to use both Formation and DemandeFormation model in my controller : DemandeFormationsController

Here is my function, it seems functionnal to me :

public function lister($id=null) {

$options=array('conditions' => array('DemandeFormation.utilisateur_id' => $id));

$this->set('demandes',$this->DemandeFormation->find('all',$options));

$this->set('formations',$this->Formation->find('all',$options));

}

lister.ctp content :

<?php

foreach($demandes as $d)

{

$id=$d['DemandeFormation']['formation_id'];

$nom=$formations['Formation'][$id];

echo $nom;

}

?>

after executing the action, i get two errors on the browser :

Undefined index: Formation [APP\View\DemandeFormations\lister.ctp]

Undefined index: [APP\View\DemandeFormations\lister.ctp]

What's wrong with my code. I'll appreciate your help and advices.

网友答案:

$formations is returned by a find('all') so it's an array indexed by numeric key, like:

$formations = array(
    0 => array(
        'Formation' => array()
    ),
    1 => /* ... */
) ;

So you can't access Formation directly, you need to be able to access it using id.

The simplest way would be to add a belongsTo relationship in your DemandeFormation model:

class DemandeFormation extends AppModel {
    /* ... */
    public $belongsTo = array(
        /* Nothing more because you kept CakePHP foreign key style. */
        'Formation'
    ) ;
    /* ... */
}

Them, you don't need to retrieve the Formation using find('all') and can access your field using, in your foreach loop, simply:

$d['Formation']['name'] 

Where name is a field in the Formation table.

相关阅读:
Top