2013-03-26 49 views
0

我有3個模型。鍵入hasMany Collector,收集器hasAndBelongsToMany Place。CakePHP找到相關模型的條件計數

我需要獲取所有類型的收藏家至少有一個地方。所以我不需要收藏家沒有地方的類型。

我在收集器模型中沒有計數字段,所以我不能使用counterCache。

回答

0

我可能在這裏弄錯了,但我相信最好的方法是利用Model :: afterFind()方法。

<?php 
// type.php (Model) 
function afterFind($results, $primary) { 
    if ($primary === true) { 
     foreach ($results as $key => $type) { 
      foreach ($type['Collector'] as $collector) { 
       // Assuming you built the associations/tables/etc. correctly and are following cake conventions. 
       if (empty($collector['Place'])) { 
        unset($results[$key]); 
        continue 2; 
       } 
      } 
     } 
    } 
} 
?> 

<?php 
// types_controller.php 

// Assuming you're using the containable behavior? If not 
// set recursive to 2. 
$this->Type->contain(array(
    'Collector' => array(
     'Place' 
    ) 
)); 
$types = $this->Type->find('all'); 

?>