如何使用CakePHP使用foreach从两个表中检索数据

时间:2019-04-22 15:23:40

标签: cakephp cakephp-3.0 cakephp-3.7

所以我需要从多个表中获取数据,但是这样做很麻烦。

我有两个模型类:

  • Thesis_Supervisor:具有主管ID和论文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浏览不同的论文
  • 将论文信息存储在变量 resultset
  • 将其返回视图

这是视图中的代码:

<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循环的结果添加到resultset变量中,但我看不到如何解决...

编辑:正如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);

它比我的原始代码简单得多,并且运行良好。

0 个答案:

没有答案
相关问题