0

I have three tables ServerScans, QueuedJobs, ReportMalware

ReportMalware has a column type which contain values like mail, abc.

I am querying ServerScans as

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

and in view separating malware report in two groups using for loop as

<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;?>

Which will take more time for execution.

What I want is to keep it in contain like

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

Is there a way to achieve this and contain same model twice based on some filter criteria?

Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

1 Answers1

2

Yes, you can do so. See the docs 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:

Here is the example taken from the official documentation:

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');
    }
}
Marijan
  • 1,825
  • 1
  • 13
  • 18