Hi All,
I’ve searched extensively on the topic of working with MANY_MANY relations, and still haven’t found an elegant answer to this problem, which should be very simple.
I’m making a MANY_MANY relation to allow a company to be listed in multiple categories for a phone book type directory. Here’s the basic table structure:
      +-------+      +----------------+     +--------+
      |company|      |company-category|     |category|
      +-------+      +----------------+     +--------+
      |id     |-----<|company_id      |  +--|id      |
      |name   |      |category_id     |>-+  |name    |
      +-------+      +----------------+     +--------+
In CGridView (admin.php), I’d like to filter the display of companies by a category they are associated with. It seems there should be a way to word the $criteria->compare() statement to do this, but I can’t get it to work. Is this not supported with MANY_MANY relations? I’ve tried the addCondition() method, but it doesn’t do anything either.
Here’s what I’ve got so far (which isn’t working for the search):
From the model:
	public function relations()
	{
		return array(
			'categories'=>array(self::MANY_MANY, 'Category', 'category-company(company_id, category_id)'),
		);
	}
	public function getRelatedCategoryNames () // IS THERE A MORE EFFICIENT WAY OF DOING THIS?
	{
		foreach ($this->categories as $k) {
			$out[] = "$k->name";
		}
		return implode(',<br />', $out);
	
	}
	public function attributeLabels()
	{
		return array(
			...
			'assignedCategories' => 'Categories',
			...
		);
	}
	public function search()
	{
		$criteria=new CDbCriteria;
		...
                //first attempt
		$criteria->compare('categories.id',$this->assignedCategories,false); // doesn't work
		...
                //second attempt (not done simultaneously with first attempt!)
		if ($this->assignedCategories) {
			$criteria->addColumnCondition(array('category_listing.id' => 
                           $this->assignedCategories));
		}
	}
From the View (admin.php) file:
<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'eld-listing-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		...
		array(
			'name' => 'assignedCategories',
			'filter'=> CHtml::listData(Category::model()->findAll(array('order'=>'name ASC')),'id','name'),
			'value' => '$data->RelatedCategoryNames',
		),
		...
Can anyone help? This is the simplest of the MANY_MANY things I need to do, and I feel dense for not being able to make it work. It would be great to have a cookbook of different scenarios. The official Class Reference doesn’t really supply scenarios, and Agile Web Application Development with YII1.1 and PHP5 only cursorily discusses MANY_MANY relations. Does anyone know of a better source?
Thanks so much in advance,
Bill