Hackneyed subject search MANY_MANY in YII , but everywhere a lot of info, all different, help me to understand

61 views Asked by At

I have tables 1) tours (id, title) 2) categories (id, title) 3) tours_categories (tour_id, category_id)

Model Tours:

public function relations () 
{ 
    return array ( 
          'Category' => array (self :: MANY_MANY, 
                               'Categories', 
                               'tours_categories (tour_id, category_id)'
          ), 
    ); 
} 

Model Categories:

public function relations () 
{ 
    return array ( 
        'Tours' => array (self :: MANY_MANY, 
                         'Tours', 
                         'tours_categories (category_id, tour_id)'
        ), 
    ); 
} 

question:

I want to search the database for the table tours_categories and select all the tours = to one category id ... how to do it correctly

In controller ToursController I want to do something like this

$tour = Tours::model()->with ('category')->findAllByAttributes (array ('category.id' => $id)); 

but it's not works of course. How to do it?

1

There are 1 answers

0
Telvin Nguyen On
$tours = Tours::model()->with(array(
            'category'=>array(
                'alias' => 'ct', //to avoid error ambiguous column category when implementing query 
                'condition'=>'ct.category_id = :cid',
                'params'=>array(':cid'=>$id
                )))
        )->findAll(); // you could put more condition for findAll, it returns array of Tour-s after filtered.

Btw, one minor thing, the name category for the relation MANY_MANY on model Tour is not congruous. It should changed to categories instead. Once you update it, you should also update above query of cause.