0

您好我有一个数据库,我在其中使用链接表来链接产品和类别。

关系如下所示:

Product      ProductCategories       Category
Id           Id                      Id
Name         ProductId               Name   
             CategoryId 

所以 productCategory 表将产品链接到类别

我的问题是当我尝试查找 ID 为 1 的类别下的所有产品时

我使用此代码,但它似乎没有工作:

$models = Products::model()->with('productcategories')->findByPk(1);

这是产品关系:

public function relations()
{
    return array(
        'productcategories' => array(self::HAS_MANY, 'Productcategories', 'ProductId'),
    );
}
4

1 回答 1

2
public function relations()
{
    return array(
        'productcategories' => array(self::HAS_MANY, 'Productcategories', 'ProductId'),
        'Categories' => array(self::HAS_MANY, 'Category', '',
            'through'=>'productcategories',
            'on' => 'Categories.Id = productcategories.CategoryId',
        ),
    );
}

// Get all Product with a Category with id = 1
$models = Products::model()->with('Categories')->findAll('Categories.Id = 1');
于 2013-10-04T06:36:31.087 回答