I have the exact same question. I want to use CActiveDataProvider to fetch objects that are in a certain category. There is a many-to-many relationship between objects and categories.
There is an objects table, categories table, and a mapping table (object_id, category_id).
I have already setup the relations() part for the Object and Category models.
And it works correctly. For example
$obj = Object::model()->findByPk(1);
$category_list = $obj->categories;
$category = Category::model()->findByPk(2);
$obj_list = $category->objects;
$obj_list contains the data that I want.
However, I’d like to get the same data by using CActiveDataProvider.
(1) I created a class which extended CActiveDataProvider. It adds a member variable named "together".
class MyDataProvider extends CActiveDataProvider
{
public $together = false;
/**
* Fetches the data from the persistent data storage.
* @return array list of data items
*/
protected function fetchData()
{
$criteria=clone $this->getCriteria();
if(($pagination=$this->getPagination())!==false)
{
$pagination->setItemCount($this->getTotalItemCount());
$pagination->applyLimit($criteria);
}
if(($sort=$this->getSort())!==false)
$sort->applyOrder($criteria);
if ($this->together)
{
return CActiveRecord::model($this->modelClass)->with($criteria->with)->together()->findAll($criteria);
}
else
{
return CActiveRecord::model($this->modelClass)->findAll($criteria);
}
}
}
The new class file from step #1 needs to be placed in the directory "protected/extensions"
Edit the file "protected/config/main.php" and include the new extension in the "import" field