一个产品 yii2 两个 parents

Two parents for one product yii2

现在我有两个表 "Category""Product"。 我让 "Product" 中的 'category_id' 等于 Category 中的 'id',所以现在在我看来它显示了该类别的所有产品。但是现在我需要一个产品在几个类别中。

在控制器中,我使用以下数据提供程序:

$dataProvider = new ActiveDataProvider([
        'query' => $query = Product::find()->where(['category_id' => $cats->id]),
        'sort'=>array(
            'defaultOrder'=>['id' => SORT_ASC],
        ),
        'pagination' => [
            'pageSize' => 9,
        ],
    ]);

关于如何实现此功能有什么建议吗?

试试这个:

$dataProvider = new ActiveDataProvider([
    'query' => $query = Product::find()->where(['id' => $product_id]),
    'sort'=>array(
        'defaultOrder'=>['id' => SORT_ASC],
    ),
    'pagination' => [
        'pageSize' => 9,
    ],
]);

OR

$dataProvider = new ActiveDataProvider([
    'query' => $query = Product::find()->where(['id' => $product_id])->groupBy(['cats->id']),
    'sort'=>array(
        'defaultOrder'=>['id' => SORT_ASC],
    ),
    'pagination' => [
        'pageSize' => 9,
    ],
]);

如果我没有理解错你的数据结构到pricipio

从 1 到 N

 Categories -> Products

现在您希望它来自 N to N 一个类别有很多产品,一个产品有很多类别。

所以我希望您创建另一个名为 Product_Categy 的 table,您可以在其中保留 2 table 的主键,并且您必须能够从N to N,你会有这样的最终方案

Categories (id, ...) -> 
Categria_Product (id, id_categoria, id_producto, ...) <- Product (id, ..)