mishmash
mishmash

Reputation: 4458

CakePHP - HABTM relationship and find()

this is my situation, I have a Post model that can belong to multiple Categories. This I figured out how to do:

class Post extends AppModel
{
    var $hasAndBelongsToMany = array('Category');
}

And the Category model:

class Category extends AppModel
{
    var $hasAndBelongsToMany = array ('Post');
}

Now, this all works fine and all that. But I just cannot figure out how to search for posts that belong to a certain category, for example "News" with the id of 1 to use in:

class CategoriesController extends AppController {
    function view ($id = 0) {
        // doesnt work
        $this->Category->Video->find ('all', array('conditions' => array('category_id' => $id));
    }
}

I've been trying to find an answer on Google and the CookBook but have found nothing yet. Does anyone know how this can be achieved?

Thank you.

Upvotes: 0

Views: 2868

Answers (3)

jwg2s
jwg2s

Reputation: 816

You can do the following which should work:

$this->Category->bindModel(array(
        'hasOne' => array(
            'CategoriesVideo'
        ),
    ));
    return $this->Video->find('all', array(
        'conditions' => array(
            'CategoriesVideo.category_id' => $id,
            ),
        ),
    ));

EDIT: Sorry, was looking at the wrong code. This should work.

Upvotes: 0

Dave
Dave

Reputation: 29121

Your easiest bet would be to search the Category itself, and allow the recursive level to also return associated Posts (or Videos, or whatever you're doing):

//in the category controller
$this->Category->find('all', array('conditions'=>array('Category.id'=>$id));

There are many options for searching against HABTM data, but the above is the easiest.

Here's the page in the CakePHP book that describes different ways to query against a HABTM relationship:

http://book.cakephp.org/1.3/view/1044/hasAndBelongsToMany-HABTM

Upvotes: 0

kaklon
kaklon

Reputation: 2432

You are performing a find on Video model, when you showed association on Category and Post models, not Video. Assuming this is a typo error:

If you want to search, as you stated, posts that are of "News" category do in posts_controller.php:

$this->Post->Category->find('all', array('conditions'=>array('Category.name'=>'News')) );

Or in the categories_controller.php

$this->Category->find('all', array('conditions'=>array('Category.name'=>'News')) );

Upvotes: 2

Related Questions