Symfony: Add Column to Doctrine Entity - php

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.

Related

How to add an entity in Symfony 2

I have made a table in a database and that table is connected to symfony2 and when I have already develop the application I have find out that I have to add column to the table called profilePicture for uploading profile pics and I have already generated the entities from the previous version of the table and now my question is
How can I add an entity from the new version of the table ?
The first thing which I advise you to make is to show the effort that you made (show at least some lines of codes).
You have to modify manually your entities and then make both following instructions in the console:
# generate getter and setter
php app/console doctrine:generate:entities YourBundle/Entity/YourClass
php app/console doctrine:schema:update --force
Finally, look at these two link, I think this is very helpful
Official documentation and this question.

How to generate a table from an entity in symfony2?

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.

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.

Doctrine [Semantical Error] Error: Class xxx has no field or association named yyy

For last few days I'm experiencing following issue with doctrine - since I am not allowed to paste any source code, I'll try to describe briefly:
I am using doctrine orm and I need to add a new column to an existing table in DB - mapping between DB and entities is done via xml mapping file - here are the steps I've proceeded:
I've added into the entity file - let's call it Entity.php - new field for that newColumn
I've added info about this newColumn into the XML mapping file as new XML element 'field'
I've executed doctrine command to change the schema of the DB based on edited mapping file
I've updated the query in EntityRepository.php file to include this new column.
When I then run the application, I am still getting this error:
[Semantical Error] Error: Class Entity.php has no field or association named newColumn
So, if I am understanding this properly, it is saying that in the Entity.php is not field newColumn to which should be the new DB column mapped.
But that is not the case, since it was the very first step I've done.
I've already tried this:
Checked there is no typo in name of the newColumn across all files
Checked the field in Entity.php has proper access modifiers - i.e. it is not private
Cache was cleared for the case that some bad version of Entity.php was stored
I've restarted apache server which the application runs on
Check your metadata cache. If you're using some external caching mechanism (like Memcached or xcache) it's probably shared across your vhosts. If one vhost populates the cache with its own mapping metadata (after apache restart), second vhost just uses it and doesn't care about different .dcm.xml mappings.
If it's your development server/vhost, it's usually much better to disable ORM caching at all (config/autoload/database.local.php).
Maybe my problem and solution would help somebody.
/* *
* #ORM\Column(name="user_id")
*/
protected $userId;
No, there was no typo in variable name. Access is correct and everything looked to be fine.
Some of you probably already see the problem.
Yes. It's /* * instead of /**. I took me about hour to find it :]
What was strange - it was working in join, but not when I have used it in where.
run this command
php bin/console doctrine:cache:clear-metadata on both APP_ENV=prod and APP_ENV=dev
Have the same problem. The solution was to replace in query condition like
LOWER(l.bank_title) LIKE :search
with its camelCase variant:
LOWER(l.bankTitle) LIKE :search

how to resolve symfony doctrine:build-schema error (Unknown relation alias table_name)

how to resolve this symfony error :
C:\inetpub\wwwroot\project\trunk\preprod\signup>php symfony doctrine:build-schema --trace
>> doctrine generating yaml schema from database
[sfException]
Unknown relation alias table_name
Exception trace:
at C:\inetpub\wwwroot\project\trunk\preprod\signup\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\cli\sfDoctrineCli.class.php:69
sfDoctrineCli->notifyException at C:\inetpub\wwwroot\ project\trunk\preprod\signup\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\ven
dor\doctrine\Doctrine\Cli.php:93
Doctrine_Cli->run at C:\inetpub\wwwroot\project\trunk\preprod\signup\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\task\sfDoctrineB
aseTask.class.php:112
sfDoctrineBaseTask->callDoctrineCli at C:\inetpub\wwwroot\project\trunk\preprod\signup\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\li
b\task\sfDoctrineBuildSchemaTask.class.php:57
sfDoctrineBuildSchemaTask->execute at C:\inetpub\wwwroot\project\trunk\preprod\signup\lib\vendor\symfony\lib\task\sfBaseTask.class.php:63
sfBaseTask->doRun at C:\inetpub\wwwroot\project\trunk\preprod\signup\lib\vendor\symfony\lib\task\sfTask.class.php:77
sfTask->runFromCLI at C:\inetpub\wwwroot\ project\trunk\preprod\signup\lib\vendor\symfony\lib\command\sfSymfonyCommandApplication.class.ph
p:76
sfSymfonyCommandApplication->run at C:\inetpub\wwwroot\project\trunk\preprod\signup\lib\vendor\symfony\lib\command\cli.php:20
include at C:\inetpub\wwwroot\project\trunk\preprod\signup\symfony:14
It is a model and cache issue (reset all configuration and erase model and data files)
rm config/doctrine/schema.yml
rm -r cache/*
rm -r data/*
rm -r lib/model/doctrine/base
symfony cc
I found a second response, using builder.php patch to have doctrine object getters in symfony 1.2 cast this error also.
those working with Symfony 1.4 will be happy to know that there's a task to clean outdated doctrine models. "./symfony doctrine:clean" will get rid of those nasty "that model don't exist anymore issues".
One of your tables appears to be referencing another table called 'table_name' (unless there's something horribly wrong with Doctrine's error output substitution). Check the relations on all of your tables to find the culprit causing this and remove the relation if it's not valid (do you actually have a table called 'table_name'?) to fix this issue.
If you have a lot of tables you can try replicating your entire database into a temporary test DB and then drop half of the tables and run the generate command again. If you don't get the error you know that chunk of tables is not the problem so drop the existing tables and restore the other half. If the same error still occurs the culprit is now within the current chunk. Continue dropping halves until you're left with just one table erroring out and you'll have found your error source.
If you're still having problems locating the exact cause of the problem can you provide your problem table's structure in SQL and also what version of Doctrine you're working with.

Categories