Let say we have three table as:

 

product:
  id;
  name;
category:
  id;
  name;
category_product:
  category_id;
  product_id;

 

 

From their structure we can know that product table and category table are MANY_MANY relation, category_product is the middle table, then how can we get the product records when we have a category.id? 

 

Set the models

Product: 

 代码

class Product extends CActiveRecord
{
    
//other codes
    public function relations()
    {
        
// NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.

        return array(
            
'categories'=>array(
                self
::MANY_MANY,
                
'Category',
                
'category_product(category_id, product_id)'
            )
,
            
'category_product'=>array(
                self
::HAS_MANY,
                
'CategoryProduct',
                
'product_id'
            )
,
        );
    }
    
//other codes
}

 

 Category:

class Category extends CActiveRecord
{
    
//other codes
    public function relations()
    {

        return array(
            
'products'=>array(
                self
::MANY_MANY,
                
'Product',
                
'category_product(category_id, product_id)',
            )
,
            
'category_product'=>array(
                self
::HAS_MANY,
                
'CategoryProduct',
                
'category_id',
            )
,
        );
    }
    
//other codes
}

相关文章: