CakePHP 2.1 find using contain with condition

心不动则不痛 提交于 2019-12-06 08:17:41

Option 1 (best option IMO):

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

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

Option 2:

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!