2017-04-25 113 views
0

我有三個表ServerScansQueuedJobsReportMalwarecakephp的3包含同一個模型兩次不同的條件而不關聯

ReportMalware具有柱type含有像mailabc值。

我查詢ServerScans作爲

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

,並考慮分離使用循環兩組惡意軟件報告

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

有沒有辦法實現這一點,幷包含同一模型兩次基於一些過濾條件?

回答

2

是的,你可以這樣做。請參閱文檔here

可以多次使用同一個表來定義不同類型的關聯關係 。例如,考慮要分開 批准尚未緩和尚未意見和那些情況:

下面是從官方文檔所採取的例子:

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'); 
    } 
} 
相關問題