cakephp 3 两次包含相同模型但条件不同而无关联

cakephp 3 contain same model twice with different conditions without association

我有三个表ServerScansQueuedJobsReportMalware

ReportMalware 有一列 type,其中包含 mailabc.

等值

我正在查询 ServerScans

$scan = $this->ServerScans->get($id, [
  'contain' => [
     'QueuedJobs',
     'QueuedJobs.ReportMalware',
  ],
]);

并考虑使用 for 循环将恶意软件报告分为两组

<h2>Mail report</h2>
<?php foreach($scan->queued_jobs->report_malware as $m): ?>
   <?php if ($m->type == 'mail'): ?>
       <?= $m->comment ?>
   <?php endif; ?>
<?php endforeach;?>

<h2>Abc report</h2>
<?php foreach($scan->queued_jobs->report_malware as $m): ?>
   <?php if ($m->type == 'abc'): ?>
       <?= $m->comment ?>
   <?php endif; ?>
<?php endforeach;?>

这将花费更多的时间来执行。

我想要的是像

一样把它收起来
$scan = $this->ServerScans->get($id, [
  'contain' => [
     'QueuedJobs',
     'QueuedJobs.ReportMalware.mail',
     'QueuedJobs.ReportMalware.abc',
  ],
]);

有没有办法实现这一点并根据某些过滤条件包含两次相同的模型?

是的,你可以这样做。请参阅文档 here.

The same table can be used multiple times to define different types of associations. For example consider a case where you want to separate approved comments and those that have not been moderated yet:

下面是官方文档中的例子:

class ArticlesTable extends Table
{
    public function initialize(array $config)
    {
        $this->hasMany('Comments')
            ->setConditions(['approved' => true]);

        $this->hasMany('UnapprovedComments', [
                'className' => 'Comments'
            ])
            ->setConditions(['approved' => false])
            ->setProperty('unapproved_comments');
    }
}