0

我有三张桌子ServerScans,,,QueuedJobsReportMalware

ReportMalware有一列type包含诸如mail,之类的值abc

我将 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',
  ],
]);

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

4

1 回答 1

2

是的,你可以这样做。请参阅此处的文档。

可以多次使用同一个表来定义不同类型的关联。例如,考虑一种情况,您希望将已批准的评论与尚未审核的评论分开:

以下是取自官方文档的示例:

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');
    }
}
于 2017-04-25T10:15:06.853 回答