选项 1(IMO 最佳选项):
你走在正确的轨道上 - 你现在需要的只是添加使用CakePHP的CouterCache http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#countercache-cache-your-count.
基本上,你设置'counterCache' => true
在你的$belongsTo
关联,并添加一个字段:singularModel_count
(在你的情况下,这将是trailer_count
领域中的movies
桌子)。然后,您可以根据该字段进行条件调整(请参阅下面更改的代码)。
CakePHP 的 CounterCache 通过在通过 CakePHP 方法添加/删除某些内容时添加/减去内容来自动跟踪其拥有的项目数量。
$this->Industry->find('all', array(
'contain' => array(
'Movie' => array(
'conditions' => array(
'Movie.trailer_count >' => 0 // <-- Notice this addition
),
'order' => 'Movie.release DESC',
'limit' => 6,
'Trailer' => array(
'limit' => 1
),
)
),
'order' => 'Industry.name ASC'
));
选项2:
另一种选择是使用 JOIN(请参阅CakePHP 加入 http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#joining-tables)。当 CakePHP 查询“contain()”调用的每个模型时,它实际上会执行单独的查询,然后在返回给您之前连接数据。因此,您不能根据子模型的条件来限制父模型,因为它们实际上是单独的查询,并且 MySQL 不会知道您在条件中尝试引用哪个表。
选项 2 的缺点是,它会使返回多个预告片之类的事情变得困难,因为您将在电影和预告片之间进行 INNER JOIN(可能)。