[Answered] Add a field without destroying data

emergingdzns - 7 months ago

I've got a module mostly complete and the client has asked for another column of data (so a new field in the form) to be added, but we already have a lot of data in the tables for the module. This particular model is ok to wipe out but so far all I've been able to do is a reinstall of the module, causing all of the data in the tables to get wiped out. I have to keep exporting, reinstalling, and then reimporting.

Is there a way to add a single field to a model as a migration and not destroy all the data in the whole module?

Answer

- 7 months ago

You can add a migration to the model with laravel command:

php artisan make:migration --addon=you_addon

Then use the php artisan make:migration --addon=you_addon , fields(), and assignments() methods to create stuff like you normally would:

$stream = $this->streams()->findBySlugAndNamespace('foo', 'bar');

$field = $this->fields()->create($attributes);

$this->assignments()->create(compact('stream', 'field');

ryanthompson - 7 months ago

You can add a migration to the model with laravel command:

php artisan make:migration --addon=you_addon

Then use the php artisan make:migration --addon=you_addon , fields(), and assignments() methods to create stuff like you normally would:

$stream = $this->streams()->findBySlugAndNamespace('foo', 'bar');

$field = $this->fields()->create($attributes);

$this->assignments()->create(compact('stream', 'field');

emergingdzns - 7 months ago

Awesome! Thanks!

huglester - 1 month ago

Hello,

first of all - thanks for the 'howto'

I tried this:

$stream = $this->streams()->findBySlugAndNamespace('products', 'products');
        $field = $this->fields()->create([
            'slug' => 'price_sale',
            'locked' => false,
            'lt' => [
                'name' => 'Išpardavimo kaina',
            ],
            'en' => [
                'name' => 'On Sale price',
            ],
        ]);

        $this->assignments()->create(compact('stream', 'field'));

And get this while migrating:

  [Symfony\Component\Debug\Exception\FatalThrowableError]  
  Call to a member function getColumnType() on null  

Any idea what I was doing wrong?

huglester - 1 month ago

looked though the mysql table for fields.. this one works, in case someone has similar problem:)

$field = $this->fields()->create([
            'slug' => 'price_on_sale',
            'namespace' => 'products',
            'type' => 'anomaly.field_type.decimal',
            'locked' => false,
            'lt' => [
                'name' => 'Išpardavimo kaina',
            ],
            'en' => [
                'name' => 'On Sale price',
            ],
        ]);