How to set initial data (not test data) in Symfony with doctrine ORM

≡放荡痞女 提交于 2020-06-22 22:33:08

问题


I am new to learning Symfony, (Symfony 4.1.6) and can't figure this out.

I have a database, and it contains a lot of tables for populating html select type inputs. they are in the database to ensure Foreign Key constraints in other records.

Is there a way to "add" this data to the database and track it? (via git) or should I resort to keeping an SQL file of just the "inserts"

I have looked at Fixtures but they seem to be mostly for dummy data. I want to insert real data. What is the "best practice" if any to do this?

****UPDATE****
I should add that the development of this project started outside Symfony, and so the database had already been manually created with a handful of records. I used bin/console doctrine:mapping:import 'App\Entity' annotation --path=src/Entity to build the entities.

Is there a similar way to "suck" the few records out of the db as well?

Maybe I just need to manually add the SQL insert statements to the first (or second) migrate file.


回答1:


In symfony, working with production database, generaly based on creating and executing migrations thanks to DoctrineMigrationBundle.

Always when you make some changes in entity, you need to update database layout. You do this by creating migration by command doctrine:migrations:diff, review migration class carefully and after that execute it on production server with command doctrine:migrations:migrate. This is about database schema.

In turn, when you need to insert, delete or update dome predefined data in database, you could create empty migration class by doctrine:migrations:generate and fill with whatever you want. Some examples are: - Write raw sql queries and execute - this is the easiest way, good for simple data - Create entities and persist by entity manager - Load database fixtures - this is the most complex solution.

In this way you do not lost data already stored in production database when you will upgrade your app.

More details in DoctrineMigrationsBundle docs: https://symfony.com/doc/master/bundles/DoctrineMigrationsBundle/index.html and also DoctrineFixturesBundle docs: https://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html




回答2:


Fixtures are good for this use-case as well, but be aware not to accidentally overwrite anything.

If you only need to populate these once, migrations are a good option. (You should be using that anyway to manage schema changes.) For example, I almost always use a migration to insert admin users and some other really "fixed" data.




回答3:


maybe you're looking for https://phinx.org/ or something like that ?

edit : http://docs.phinx.org/en/latest/migrations.html#inserting-data



来源:https://stackoverflow.com/questions/53090291/how-to-set-initial-data-not-test-data-in-symfony-with-doctrine-orm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!