Laravel 8syncWithPivotValues() 无法按预期工作

问题描述 投票:0回答:1

我有三个表:audiments、company 和audience_company。数据透视表audience_company 包含列audience_id、company_id 和type。所以我根据类型列区分数据。数据透视表中的所有三列上方还有唯一索引。

但是当我使用syncWithPivotValues()方法同步数据透视表中的值时,仅插入最后一个类型,导致第一个类型被删除。代码如下所示:

$audience->companies()->syncWithPivotValues([1, 2], ['type' => 'PURCHASE']);
$audience->companies()->syncWithPivotValues([1, 2], ['type' => 'ACTIVE']);
$audience->companies()->syncWithPivotValues([1, 2], ['type' => 'FAVORITE']);

最后,最后一个最喜欢的类型会重写所有以前的类型。有人可以告诉我如何正确地做吗?

synchronization pivot laravel-8
1个回答
0
投票

我使用 detach() 和 Attach() 方法来完成它。代码如下:

protected function syncRelatedCompanies(Audience $audience, array $data)
{
    $audience->companies()->detach();  // Remove all from audience_company table
    $purchase_ids = $data['purchase_ids'] ?? [];
    $interaction_ids = $data['interaction_ids'] ?? [];
    $favorite_ids = $data['favorite_ids'] ?? [];

    $audience->companies()->attach($purchase_ids, ['type' => 'PURCHASE']);
    $audience->companies()->attach($interaction_ids, ['type' => 'INTERACTION']);
    $audience->companies()->attach($favorite_ids, ['type' => 'FAVORITE']);
}
© www.soinside.com 2019 - 2024. All rights reserved.