laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.5k stars 11.01k forks source link

Attempting to save a deleted model with a $withCount property fails #22427

Closed Miguel-Serejo closed 6 years ago

Miguel-Serejo commented 6 years ago

Description:

When trying to save a previously deleted model instance that has a $withCount property, a SQL "Column not found" exception is thrown be cause Laravel attempts to insert the model with the related_count column

Steps To Reproduce:

Delete an instance of a model that includes a $withCount property and then call ->save() on it.

>>> $country->refresh()
=> App\Country {#1032
     id: 2,
     name: "test",
     created_at: "2017-11-28 13:34:26",
     updated_at: "2017-11-28 13:34:26",
     deleted_at: null,
     holidays_count: 1,
   }
>>> $country->delete();
=> true
>>> $country->save();
Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'holidays_count' in 'field list' (SQL: insert into `countries` (`id`, `name`, `created_at`, `updated_at`, `deleted_at`, `holidays_count`) values (2, test, 2017-12-14 09:52:22, 2017-12-14 09:52:22, , 1))'
themsaid commented 6 years ago

You'll need to clean the instance before you save it, the instance was deleted you can't re-create it like that, it might have some attributes loaded like the case you shared.