user2358261
user2358261

Reputation:

Yii search by one value in many_many relation, and get all data from this relation

I have three table product , category , product_category

and in product model I add this relation

return array( 'categories' => array(self::MANY_MANY, 'Category', 'product_category(product_id, category_id)') );

Now I want to use search by category if category select.

In product actionIndex i add this code

$criteria=new CDbCriteria;
if($_GET['name'])
{
    $criteria->with = array('categories');
    $criteria->together = true;
    $criteria->addCondition('categories.name = :name');
    $criteria->params = array(':name'=>$_GET['name']);
}

$dataProvider=new CActiveDataProvider('Product',array(
        'pagination'=>array(
                'pageSize'=>10,
        ),
        'criteria' => $criteria
));

$this->render('index',array(
    'dataProvider'=>$dataProvider,
));

If i made search, categories loads in eager load, and has no categories other than searching.
How search Product by category, but in $data->categories has all categories, without loads them by second relation in view, how Andrey Vorobyev says?

Sorry for bad english

Upvotes: 1

Views: 618

Answers (2)

user2358261
user2358261

Reputation:

I found the answer

if i use $criteria->with = array('categories'=>array('select' => false)) and call $data->categories, it do lazy loading and everything is fine.

Upvotes: 1

Andrey Vorobyev
Andrey Vorobyev

Reputation: 886

First, that i think, is make two same relations with different names: one for search, another for show.
Because, when we set condition, we filter post by category, and we can't get all categories. But you will have one more relation, you can get all categories in lazy load, when you were print posts.

Upvotes: 0

Related Questions