【问题标题】:Retrieving data using relationships in Yii PHP在 Yii PHP 中使用关系检索数据
【发布时间】:2013-10-03 18:06:08
【问题描述】:

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

关系如下所示:

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'),
    );
}

【问题讨论】:

  • 模型中的关系是如何定义的?
  • @MarkWinterbottom 我更新了我的问题。
  • 什么不起作用?它不返回任何东西吗?

标签: php yii foreign-key-relationship


【解决方案1】:
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');

【讨论】:

  • 感谢这帮助了我。但是我不需要类别关系(但是我将来可能会使用它)。我最后使用的代码是: $models = Products::model()->with('productcategories')->findAll('productcategories.Id = 1');
  • 哦,我现在明白了。我希望这会对你有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多