Hi,
I trying to import a json file with a belongsToMany relation. Here is a function that processes all relationship fields:
protected $belongsToManyFields = ['categories', 'authors'];
protected function processRelations($model, $data)
{
foreach ($this->belongsToManyFields as $field) {
if (isset($data[$field]) && !empty($data[$field])) {
$ids = explode(',', $data[$field]);
$relatedIds = array_map('trim', $ids);
$model->$field()->sync($relatedIds);
}
}
}
When I don’t fill the “category” field in the json file or this field has only one value, e.g. 1 the import works fine, but when I have the values separated by commas I get an error:
SQLSTATE[01000]: Warning: 1265 Data truncated for column 'categories_id' at row 1 (SQL: insert into `xyz_news_news_categories` (`categories_id`, `news_id`) values (1,2, 1))
json file:
[
{
"name": "Test 1",
"slug": "test1",
"categories": "1,2"
},
{
"name": "Test 2",
"slug": "test2",
"categories": "1"
}
]
The same error appears when importing a CSV file