Yii2 GridView 中的重复记录

Duplicated records in Yii2 GridView

它工作得很好,但我不得不在现有的 order1 table 中重新导入数据,它与 [=15= 上的 order_item table 有关] 和 order_item.location_id = location.id

因此,为了获取 order1 table 在 GridView 中的位置,我将关系定义如下:

public function getLocation() {         
    return $this->hasOne(Location::className(), ['id' => 'location_id'])->viaTable('{{%order_item}}', ['order_id' => 'id']);            
}

现在我在 GridView 中有多个记录。为 GridView 形成的查询类似于:

SELECT `order1`.* 
FROM `order1` 
    LEFT JOIN `order_item` ON `order1`.`id` = `order_item`.`order_id`
    LEFT JOIN `location` ON `order_item`.`location_id` = `location`.`id` 
where 1 ORDER BY `id` DESC 
LIMIT 20;

如何将其修复为内部连接或其他方式,以便它 returns 仅从 order1 table?

记录一次

我在 GridView 中使用 location.location_title

注意:每个订单有多个订单项目。

也试过:

public function getOrderItem()
{
    return $this->hasMany(OrderItem::className(), ['order_id' => 'id']);
}

public function getLocation()
{
    return $this->hasOne(Location::className(), ['id' => 'location_id'])
        ->via('orderItem');
}

您需要在搜索模型中添加GROUP BY以确保查询结果中的订单不会重复:

$query->groupBy('order1.id');

虽然 hasOne() 似乎不正确(如果一个订单可以有多个项目,那么它也可以有多个位置),将其更改为 hasMany() 不会修复 GridView 结果。您需要注意一对多或多对多关系,通常您需要使用 GROUP BY 删除重复项或调整您的数据库结构或在搜索模型中加入,以避免这种情况。


顺便说一句:在关系定义 (getLocation()) 中添加 groupBy() 几乎总是不正确的。这不是处理主要模型结果分组的关系定义的工作(你几乎可以肯定它会产生延迟加载问题)。