Adding conditions to Containable in CakePHP

六月ゝ 毕业季﹏ 提交于 2019-12-05 06:34:54

TLDR: do your find on Genre and contain it's Movies, or use joins() - doing your search on Movies and containing Genre with conditions won't work for the results you want.


Explanation:

Below is your corrected 'contain' code, but more importantly, doing a 'contain' on Genre won't return the results you're looking for.

What it does - limits the contained genres based on your condition... so it will pull ALL movies, and contain the genres that match $genre.


Solutions (depending on your needs):

Solution 1)

  • Do a find() on Genre, with the condition, and contain it's movies. This will pull the genre that matches, then only the movies that are related to it.

Solution 2) - the one I'd recommend

  • Use 'joins()':

$conditions = array();
$conditions['joins'] = array(
    array(
        'table' => 'genres_movies', //or movie_genres if you've specified it as the table to use
        'alias' => 'GenresMovie',
        'type' => 'INNER'
        'conditions' => array(
            'GenresMovie.movie_id = Movie.id'
        )
    ),
    array(
        'table' => 'genres',
        'alias' => 'Genre',
        'type' => 'INNER',
        'conditions' => array(
            'Genre.id = GenresMovie.genre_id',
            'Genre.name = "' . $genre . '"'
        )
    )
);
$this->Movie->find('all', $conditions);

Your edited (corrected imo) 'contain' example

//edited example
$genre = "drama";

$options = array(
    'contain' => array(
        'Genre' => array(
            'conditions' => array('Genre.name' => $genre)
        )
    ),
    'recursive' => -1,
    'limit' => 10
);
$this->paginate = $options;
$this->set('movies', $this->paginate('Movie'));
  1. you don't "contain" the model you're doing the find on (ie I removed 'Movie' from your contain array).
  2. you only contain models, not things like "MovieGenre.Genre" (I can't think of any time you would use '.' concatenated models)
  3. recursive needs to be -1 to use Containable - you should set this to -1 in the AppModel and forget the concept of recursive - it's bad
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!