我正在使用cake php 2开发一个网络应用程序。
我在显示2个表中的数据时遇到问题......
我的模特:
<?php
class Discipline extends AppModel{
public $hasMany = "Student";
}
?>
<?php
class Student extends AppModel{
public $belongsTo = array(
"Discipline" => array(
"className" => "Discipline",
"foreignKey" => "discipline_id"
)
);
}
?>
这是我的学生控制器:
<?php
class StudentsController extends AppController{
function admin_index(){
if($this->request->is('put') || $this->request->is('post')){
$student = $this->request->data['Student'];
if($this->Student->save($this->request->data)){
$this->Session->setFlash("L'eleve a bien été modifié","notif");
}
}
$d['student'] = $this->Student->find('all',array(
'contain' => "Discipline"
));
$this->set($d);
}
}
我正在尝试使用此视图显示学生的数据:
<?php
foreach($student as $k => $v){
$v = current($v);
echo "<td>Action</td>";
echo "<td>Label</td>";
echo "<td>".$v['nom']." ".$v['prenom']."</td>";
echo "<td>".$v['sexe']."</td>";
echo "<td>".$v['naissance']."</td>";
echo "<td>".$v['Discipline']['designation']."</td>";
echo "<td>".$v['comite']."</td>";
echo "<td>".$v['classe']."</td>";
echo "<td>".$v['elite']."</td>";
echo "<td>".$v['alerte']."</td>";
echo "<td>".$v['quota1']."</td>";
echo "<td>".$v['quota2']."</td>";
echo "<td>".$v['total']."</td>";
echo "<td>Pris</td>";
echo "<td>Restant</td>";
echo "<td>Supp</td>";
}
?>
但我在这一行有一个问题:
echo "<td>".$v['Discipline']['designation']."</td>";
它说错误:
notice (8): Undefined index: designation [APP\View\Students\admin_index.ctp, line 47]
我习惯于在cakephp 3上进行开发,我对这个错误感到非常尴尬......如何从学生视图中显示来自Disciplines表的数据?
有什么想法吗? THX
编辑:我在StudentsController上进行了调试,找到了我想要显示的数据:array(
'student' => array(
(int) 0 => array(
'Student' => array(
'id' => '2',
'prenom' => 'Jean',
'nom' => 'Michel',
'sexe' => '1',
'naissance' => '2015-08-02',
'age' => '12',
'classe' => '1',
'discipline_id' => '1',
'comite' => 'test',
'categorie' => 'test',
'elite' => true,
'alerte' => 'test',
'quota1' => '12',
'quota2' => '12',
'total' => '24',
'note' => 'tete'
),
'Discipline' => array(
**'id' => '1',
'designation' => 'Alpin'**
)
)
)
)
答案 0 :(得分:0)
我认为你应该改变观点
变化:
foreach($student as $k => $value){
$v = current($value);
为:
foreach($student as $k => $v){
$v = current($v);
并改变:
echo "<td>".$v['Discipline']['designation']."</td>";
到
echo "<td>".$value['Discipline']['designation']."</td>";
你用第一个找到的数组覆盖变量$ v,所以$ v将是$ v ['Student']
我自己不会使用current进入CakePHP的数组,但是到处使用$ v ['Student']