【问题标题】:cakephp 3 contain same model twice with different conditions without associationcakephp 3 两次包含相同的模型,不同的条件没有关联
【发布时间】:2017-04-25 09:08:51
【问题描述】:

我有三张桌子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',
  ],
]);

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

【问题讨论】:

    标签: cakephp model-associations cakephp-3.4


    【解决方案1】:

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

    同一张表可以多次用于定义不同类型的 协会。例如考虑一个你想分开的情况 已批准的 cmets 和尚未审核的 cmets:

    以下是官方文档中的示例:

    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');
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多