syncWithPivotValues() do not work as expected I have three tables: audiences, companies and audience_company. Pivot table audience_company contains columns audience_id, company_id and type. So I differentiate data according type column. There is also unique index above all three columns in pivot table.
But as I use syncWithPivotValues() method to sync values in pivot table only the last type is inserted cause first types ar deleted. The code looks like this:
$audience->companies()->syncWithPivotValues([1, 2], ['type' => 'PURCHASE']);
$audience->companies()->syncWithPivotValues([1, 2], ['type' => 'ACTIVE']);
$audience->companies()->syncWithPivotValues([1, 2], ['type' => 'FAVORITE']);
At the end the last favorite type rewrites all previous types. Can somebody tell me please how to do it properly?
haven`t tested this, it is a long shot, so it might not work, but give it a try:
$audience->companies()->sync([
1 => ['type' => 'PURCHASE'],
2 => ['type' => 'PURCHASE'],
1 => ['type' => 'ACTIVE'],
2 => ['type' => 'ACTIVE'],
1 => ['type' => 'FAVORITE'],
2 => ['type' => 'FAVORITE'],
]);
or have a look at syncWithoutDetaching()
@s4muel I did it this way
$audience->companies()->detach(); // Remove all from audience_company table
$purchase_ids = isset($data['companies_purchase_ids']) ? (array)$data['companies_purchase_ids'] : [];
$interaction_ids = isset($data['companies_interaction_ids']) ? (array)$data['companies_interaction_ids'] : [];
$favorite_ids = isset($data['companies_favorite_ids']) ? (array)$data['companies_favorite_ids'] : [];
$audience->companies()->attach($purchase_ids, ['type' => Audience::COMPANY_TYPE_PURCHASE]);
$audience->companies()->attach($interaction_ids, ['type' => Audience::COMPANY_TYPE_INTERACTION]);
$audience->companies()->attach($favorite_ids, ['type' => Audience::COMPANY_TYPE_FAVORITE]);
Please sign in or create an account to participate in this conversation.