It’s because on first record the $model->isNewRecord is true and the record is added to the database… but on all other loops isNewRecord is false… and the record is just updated not added…
You can set $model->isNewRecord to false… or generate a new model on every loop $model=new YourModel;
If isNewRecord is false… than an update is performed instead of insert…
You are getting the integrity constraint validation because you are trying to insert a primary key value that already exists in the database… you cannot have two equal primary key values!
The first entry is recorded with a new primary key, and it want record the second with the same id as the first one, even if I set isNewRecord to true.