所以我需要从多个表中获取数据,但我在这样做时遇到了麻烦。
我有两个模型类:
- Thesis_Supervisor : 有一个主管 id 和一个论文 id
- 论文:有关于论文的所有信息(id,主题,作者......)
我想做的是,考虑到一个主管身份,我想知道他监督的论文以及关于论文的所有信息。
这是我的代码:
在我的论文主管控制器中,我有这个功能:
public function listOfThesisBySupervisor($id=null){
$result = $this->ThesisSupervisor->find('all', [
'conditions' => ['supervisor_id' => $id],
]);
$resultset=array();
foreach($result as $row){
$this->loadModel('Theses');
$query = $this->Theses->find('all');
array_push($resultset,$query->where(['id' => $row->these_id])->toArray());
}
$this->set('Thesis', $resultset);
}
}
这个功能是:
- 将所有论文链接到给定的主管
- 使用 foreach 来完成不同的论文
- 将论文信息存储在变量结果集中
- 将其返回到视图
这是视图中的代码:
<div class="thesis index large-9 medium-8 columns content">
<h3><?= __('Thesis') ?></h3>
<table cellpadding="0" cellspacing="0">
<thead>
<tr>
<th scope="col"><?= $this->Paginator->sort('id') ?></th>
<th scope="col"><?= $this->Paginator->sort('sujet') ?></th>
<th scope="col"><?= $this->Paginator->sort('type') ?></th>
<th scope="col"><?= $this->Paginator->sort('date_debut') ?></th>
<th scope="col"><?= $this->Paginator->sort('date_fin') ?></th>
<th scope="col"><?= $this->Paginator->sort('signature') ?></th>
<th scope="col"><?= $this->Paginator->sort('auteur_id') ?></th>
<th scope="col" class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($Theses as $thesis): ?>
<tr>
<td><?= $this->Number->format($thesis->id) ?></td>
<td><?= h($thesis->subject) ?></td>
<td><?= h($thesis->type) ?></td>
<td><?= h($thesis->beginning) ?></td>
<td><?= h($thesis->ending) ?></td>
<td><?= h($thesis->sign) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
因此,使用此代码,我确实找到了正确数量的结果,但在视图中无法识别它们,我在论文的每个领域都得到了这种类型的错误:
Trying to get property 'id' of non-object
我尝试了许多不同的语法来做到这一点(我尝试删除 foreach 中的 ->toArray 以获得一个对象,但我对论文的每个字段都有一个未定义的属性错误),但它们都不起作用。我认为问题是将每个 foreach 循环的结果添加到结果集变量中,但我不知道如何解决它......
编辑:正如 ndm 在他的评论中建议的那样,我更多地研究了关联(因为我的模型类与关联链接在一起),这里是我的最终代码:
$result = $this->ThesisSupervisor->find('all', [
'conditions' => ['supervisor_id' => $id],
'contain' => ['Thesis']
]);
$resultset=array();
foreach ($result as $row){
$resultset[]=$row["thesis"];
}
$this->set('Theses', $resultset);
它比我的原始代码简单得多,并且运行良好。