CakePHP 2.1找到使用包含条件 [英] CakePHP 2.1 find using contain with condition

查看:168
本文介绍了CakePHP 2.1找到使用包含条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号。


  1. 行业(id,姓名)

  2. id,name,industry_id)[行业有很多电影]

  3. 预告片(id,name,movie_id)[电影有许多预告片]

我需要为每个行业找到6个最新预告片。

I need to find 6 latest trailers for each Industry. Every movie does not need to have a trailer or can have multiple[0-n].

结果必须包含至少一个预告片的电影数组。

The results must contain array of movies with atleast one trailer.

$this->Industry->find('all', array(
    'contain' => array(
        'Movie' => array(
            'Trailer' => array(
                'limit' => 1
            ),
            'order' => 'Movie.release DESC',
            'limit' => 6
        )
    ),
    'order' => 'Industry.name ASC'
));


推荐答案

您在正确的轨道上 - 您现在需要的是添加使用 CakePHP的CouterCache

You were on the right track - all you need now is the addition of using CakePHP's CouterCache.

基本上,你设置'counterCache'=>在 $ belongsTo 关联中添加一个字段: singularModel_count ,它将是电影表中的 trailer_count 字段。

Basically, you set 'counterCache' => true in your $belongsTo Association, and add a field: singularModel_count (in your case, it would be trailer_count field in the movies table). Then, you can just condition against that field (see altered code below).

CakePHP的CounterCache通过添加/减去任何时间来自动跟踪它有多少项目通过CakePHP方法添加/删除。

CakePHP's CounterCache automatically keeps track of how many items it has by adding/subtracting any time something is added/deleted via a CakePHP method.

$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 JOINs )。当CakePHP查询由contains()调用的每个模型时,它实际上会执行单独的查询,然后在返回给您之前连接数据。因此,你不能根据子模型的条件限制父模型,因为它们实际上是单独的查询,MySQL不知道你在你的条件中要引用什么表。

The other option is to use JOINs (see CakePHP JOINs). When CakePHP queries each model called by "contain()", it actually does separate queries, then joins the data before returning to you. Because of that, you cannot limit the parent model based on conditions against the child model, because they're actually separate queries, and MySQL won't know what table you're trying to refer to in your conditions.

选项2的缺点是,它会使很难做的事情,如返回多个预告片,因为你会做一个INNER JOIN(可能)在电影和预告片之间。

The downside to Option 2 is that it will make it difficult to do things like returning multiple trailers, since you'd be doing an INNER JOIN (likely) between Movie and Trailer.

这篇关于CakePHP 2.1找到使用包含条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆