The issue you're encountering with the upsert() method in Laravel is likely due to the incorrect specification of the unique key constraints and the conflict columns. The upsert() method requires you to specify the unique columns that should be used to determine if a record should be updated or inserted.
In your case, the unique constraint is on the combination of model_type, model_id, and owner_id. Therefore, you should use these columns as the conflict columns in the upsert() method.
Here's the corrected code for your controller:
Shareholder::upsert([
[
'model_type' => 'translator',
'model_id' => 1,
'owner_id' => 100,
'percentage' => 20,
]
],
['model_type', 'model_id', 'owner_id'],
['percentage']);
Explanation:
- Data Array: The data array should be wrapped in an additional array to ensure it is treated as a batch insert.
-
Conflict Columns: The conflict columns should be
['model_type', 'model_id', 'owner_id']because these are the columns that form the unique constraint. -
Update Columns: The columns to be updated in case of a conflict should be
['percentage'].
This should ensure that the upsert() method correctly updates the existing record if a conflict is found based on the unique key constraint, rather than inserting a duplicate record.