How to generate a table from an entity in symfony2? - php

This might be a dumb question but I'm clueless as to how to go about this.
I've got the entity "MailEntity". However, My database does not contain a table that corresponds with this entity yet.
Question
I would like to know how to generate the table that corresponds with the Entity I created. I've been looking for this but whatever I search on google, the same results seem to pop up constantly.
Update
I've come to know that I can achieve what I want by doing php app/console doctrine:schema:update. Adding the --dump-sql parameter will dump the sql before the schema is actually updated.
However, I would like to do this for a single Bundle. A single Entity would be even better. I just want to create a table from the MailEntity without changing anything else in the database.

If you already have the entity classes ready to go, simply run:
app/console doctrine:schema:update
This should list all the queries doctrine needs to run to create the tables. Run the command with the --force flag to execute them. It's documented here
It might be worth looking at the doctrine migrations bundle, which allows you to diff the current DB status with the entities, and generate migration scripts based on that diff see the docs

You could use php app/console doctrine:schema:update.
This command will tell doctrine to execute the necessary SQL so that your database reflects your doctrine schema. Add --force to actually execute the query.
If you want to check the generated SQL command first, you can use --dump-sql. It will print what would be executed with --force.
Related documentation you may read for further information
EDIT : If you want to create the table for a single entity, the easiest way is to dump the generated sql with --dump-sql and then extract the line responsible of your MailEntity table creation, then execute it manually.
I would not recommend to do it this way though, you should let Doctrine synchronise your database on its own. This kind of tricks may result in errors in your database.

Related

Map database views in Doctrine Migrations Bundle

There does not seem to be proper documentation available on how to configure and use database views with the doctrine migrations bundle.
One probably is not able to map SQL statements which will end up creating/updating a database view (from the sql given somewhere) when migrations:diff and migrations:migrate are run.
If an entity is mapped to a database view with the #table(name="view_name") markup, it ends up causing an error / new table being attempted, instead of understanding that its a database view being used.
Is there a solution? Am I missing something?
I'm not sure that doctrine can get out of the box views. For all I know, you'll have to cheat.
Or:
I think you have to write the migration script yourself.You can generate an empty one and then write the create-statements into it.
In the repository you integrate native sql. The result you map to your entity or DTO.
https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/reference/native-sql.html

Symfony 4: how to safely 'join' migrations together? / remove migrations in between the first and last?

I was recently tweaking around with my DB and noticed that I made 5 migrations on top of my existing 2. So 7 in total, m1, m2, ..., m7. From these 5, I only want the latest version. So I was thinking I could remove m3, m4, m5, m6, m7 and migrate again, which will result in m3 that already contains the final version that I'm happy with. Now I have never done this before and was wondering what is the safest way to do it?
I'm using PHPStorm. Could I manually remove them (right click in PHPStorm then Delete) and then go to the command line and do php bin/console doctrine:migrations:migrate? Or do I need to do php bin/console doctrine:schema:update? Or is this really a bad idea?
No, generally you shouldn't do either of those. Let me start by clearing up what seems like a misconception: a migration doesn't contain a full database schema, only the queries necessary to bring the database from one version to the next. This system allows for database changes to be managed and versioned. So you should be starting to see some problems with this:
A migration might depend on a previous one. E.g. v1 adds an entity and v2 adds a new field. If you remove v1, v2 will be broken and needs to be removed as well.
Since a database migration usually goes hand in hand with an object model change, you will have to revert the model as well, otherwise you'll find mapping problems with non existent fields.
This might be acceptable during the design phase when you don't have any functionality yet. You can revert an individual migration using bin/console doctrine:migrations:execute --down <version>. This is usually done while testing changes if adjustments need to be made. But usually when that change hasn't been committed yet.
Doctrine keeps track of migrations using a database table called migration_versions. By naming them with a date, it can order them and apply them sequentially. Whenever a migration is executed, it adds the migration name to this table. When you roll it back, it deletes it from the table, along with the fields in the migration itself. Keep in mind that even though you can rollback a migration, it doesn't mean everything will be as it was. If a migration drops a column, the column will be recreated on rollback, but the data will be lost.
As for "can it be done"? Yes. If you really really want to, have read the documentation thoroughly and are aware of all this.
So, since your question is about merging migrations, let's tackle your actual options:
Could I manually remove them (right click in PHPStorm then Delete) and then go to the command line and do php bin/console doctrine:migrations:migrate?
No, this won't work. migrate will apply available migrations. They won't be any and, as explained, the revisions will still be in the table and its changes applied.
Or do I need to do php bin/console doctrine:schema:update?
This won't do anything either, since it will compare the model with the database and find that they match.
In any case, you will need to revert them first and then create an equivalent one. The command for that is doctrine:migrations:diff. This will compare the model with the schema and generate a migration to get the database in sync. And for this to work you will need to execute --down your migrations first, otherwise they won't be any changes, but potentially losing some data in the process.
If you work in a team, they will be seeing migrations disappear. Some might even be behind in the history and not applied all the migrations. This will soon become a management pain.
There is a rollup command that (with my understanding and never actually used it) cleans stale migrations from the table, dumps a full schema and applies it. This will be your best bet, but be aware that this most like will delete your data.
You could also combine your migrations manually. They are just classes with an up and down methods. Combine all function bodies, apply the cleanup process and call it a day.
Now, if you want to do this it shouldn't be much of a problem. Just replace your outdated versions with your new one and warn everybody about it. But if what you want is to do as they never existed at all and keep a neat commit history, then that's when your teammates will potentially want to kill you, as it will involve rewriting history. When you do that, they will have to rebase all their work.
If you want to do it:
Make backups
Introduce your changes as early as possible to avoid breaks. Is ok if there are some unused fields in the database for a while, until the model commits catch up. If you do it late and some object need it, someone might be forced to create a migration and break yours in the process.
Get it right (preferably on the first try). Don't push until you have tested extensively.
Make backups
Reference for the console commands
There isn't a "safe" way of doing it, but if you haven't deployed the migrations then you can safely throw away a series of auto-generated migrations and regenerate them. Just be careful you don't throw away manual migration SQL at the same time.
Normally during the design stage we will:
Use doctrine:schema:update --force until things are fairly stable
After they are stable, we reset the development database from a snapshot
Run doctrine:migrations:diff and then add manually migration queries where necessary
May be you need to ignore all your migrations and focus on your last state of database schema. If this is what you are wondering to have in final, then you could just hit:
php bin/console doctrine:schema:update --dump-sql to get the corresponding SQL statement, or hit php bin/console doctrine:schema:update --force to apply it actually on database.
In general yes you can.
But you should know about that the Doctrine/Migration save executed migrations in DB . So you should remove unnecessary migration files (possible combine all queries into one), after that update database.
Table name by default "doctrine_migration_version" just delete unnecessary version rows

Symfony: Add Column to Doctrine Entity

I'm trying to learn the basics of Symfony, and have come across a problem that baffles me.
I'm trying to write Data to a SQL Table, following (mostly) the instructions from the documentation ( http://symfony.com/doc/current/book/doctrine.html ). I created an entity via
$ php bin/console doctrine:generate:entity
and it is mapped to my DB Table correctly, I can read and write, no problem. After that I added a column to my table and the corresponding lines to my Entity:
/**
* #var string
*
* #ORM\Column(name="User_Credentials", type="text")
*/
private $userCredentials;
Then I tried creating the setters and getters, but no changes were made, just a backup of my Entity. So I added getter and setter myself, but when attempting to write to the DB the corresponding column is ommited, remaining empty. No errors are given. I checked and re-checked for typos or other sytax errors, but could not find any. When doing
$ php bin/console doctrine:schema:update --dump-sql
I get
ALTER TABLE st_users DROP User_Credentials;
So it seems my Column is completely ignored. I cleared the cache repatedly, which changed nothing. I am, obviously, lost. Any hint as to the right path will be appreciated.
Thank you.
You can use DoctrineMigrationsBundle for this operations. This bundle will manage your database operations. (Drop, Alter, Create etc.)
Anyway, when you add a new column you can try this: php app/console doctrine:schema:update --force
Well, this is embarassing...
Anyway, if someone else is having the same problem: I had a Tab before the '#ORM\Column' annotation, and it seems the parser can't handle that. Deleting the tab and adding a space did the trick.
Mert's answer is correct anyway, so I will mark it as the right answer.
I added a column to my table and the corresponding lines to my Entity
The concept of Symfony is to add column only to entity, but not to table itself.
Then, when you execute
php bin/console doctrine:schema:update --force
Symfony would detect that you have a new column and it will add column to the table automatically.
PS. Regarding clearing a cache. In case apc cache is enabled in Symfony - you also need to restart Apache or php-fpm process. Otherwise it will ignore new annotations.

Symfony2 doctrine update schema from specific entity

If I run
php app/console doctrine:schema:update --force
It will update my database from all entities.
I need to update database only for the User entity, what is the solution?
One solution is to define a custom entity manager and then pass that entity manager to
php app/console doctrine:schema:update --force --em="custom"
But maybe it exists something faster without defining a custom entity manager?
According to the command documentation, there is no such option. If this is something you have to do only once, I'd suggest to use the --dump-sql option to get the required SQL instructions, and manually run the ones you need.
P.S. I fail to understand what's the reason to only update the schema for an entity, and leave all the rest of entities not sync'd with the database. That sounds like a recipe for getting db errors.
You can manually use the Doctrine SchemaTool class to generate an SQL diff based only on a single entity. You’ll need access to Doctrine’s EntityManager – the example below assumes access to Symfony’s container.
use Doctrine\ORM\Tools\SchemaTool;
$em = $this->container->get('doctrine')->getManager();
$schemaTool = new SchemaTool($em);
$metadata = $em->getClassMetadata(YourEntity::class);
$sqlDiff = $schemaTool->getUpdateSchemaSql([$metadata], true);
The variable $sqlDiff will now contain an array of SQL statements that are needed to bring the database schema up to date with your entity mapping.
The second argument passed to SchemaTool::getUpdateSchemaSql() is important – without it, the default behaviour would be to generate DROP TABLE statements for every other table that appears in your database.

Rebuild model without loss data in MySQL for Symfony

What is the best way to rebuild a model without loss data in MySQL for Symfony?
What if I have a big site, and a lot of data in the database and I would like after six months to add few new fields to database?
You can use migration.
Doctine manual
Symfony task for migrations
Slideshare presentation
Slideshare presentation
So you need write migrations, migrate, and build your models, forms, etc.
I suggest you use #denys281 for Symfony1.4 ....in Symfony2 however its VERY simple ... just use the command :
php app/console doctrine:schema:update --force
It compares what your database should look like (based on the mapping information of your entities) with how it actually looks, and generates the SQL statements needed to update the database to where it should be. In other words, if you add a new property with mapping metadata to Product and run this task again, it will generate the "alter table" statement needed to add that new column to the existing product table. So it doesnt remove any data
There is also a DoctrineMigrations bundle for Symfony2 if you fancy that route -> http://symfony.com/doc/current/bundles/DoctrineMigrationsBundle/index.html

Categories