Entities aren’t updated after changes - symfony

I'm new to using Symfony, and today I encountered a problem, I can not change the properties of my entities : Doctrine doesn't want to insert the changes into my database...
I look for answers like for example here, but I did not find the solution.
As I am new, I tried again from a blank project:
I create a new entity:
luc#Lucs-MacBook-Pro:~/SymfonyTest|master⚡
⇒ symfony console make:entity
Class name of the entity to create or update (e.g. TinyChef):
> Product
created: src/Entity/Product.php
created: src/Repository/ProductRepository.php
Entity generated! Now let's add some fields!
You can always add more fields later manually or by re-running this command.
New property name (press <return> to stop adding fields):
> name
Field type (enter ? to see all types) [string]:
>
Field length [255]:
>
Can this field be null in the database (nullable) (yes/no) [no]:
>
updated: src/Entity/Product.php
Add another property? Enter the property name (or press <return> to stop adding fields):
>
Success!
Next: When you're ready, create a migration with make:migration
Then I make the migration:
luc#Lucs-MacBook-Pro:~/SymfonyTest|master⚡
⇒ symfony console make:migration
Success!
Next: Review the new migration "src/Migrations/Version20191122111110.php"
Then: Run the migration with php bin/console doctrine:migrations:migrate
See https://symfony.com/doc/current/bundles/DoctrineMigrationsBundle/index.html
I run it:
luc#Lucs-MacBook-Pro:~/SymfonyTest|master⚡
⇒ symfony console doctrine:migration:migrate
Application Migrations
WARNING! You are about to execute a database migration that could result in schema changes and data loss. Are you sure you wish to continue? (y/n)y
Migrating up to 20191122111110 from 0
++ migrating 20191122111110
-> CREATE TABLE product (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB
++ migrated (took 36.5ms, used 16M memory)
------------------------
++ finished in 39ms
++ used 16M memory
++ 1 migrations executed
++ 1 sql queries
And I added a new property to my entity:
luc#Lucs-MacBook-Pro:~/SymfonyTest|master⚡
⇒ symfony console make:entity
Class name of the entity to create or update (e.g. FierceGnome):
> Product
Your entity already exists! So let's add some new fields!
New property name (press <return> to stop adding fields):
> description
Field type (enter ? to see all types) [string]:
>
Field length [255]:
>
Can this field be null in the database (nullable) (yes/no) [no]:
>
updated: src/Entity/Product.php
Add another property? Enter the property name (or press <return> to stop adding fields):
>
Success!
Next: When you're ready, create a migration with make:migration
When I try to create my migration it doesn't work:
luc#Lucs-MacBook-Pro:~/SymfonyTest|master⚡
⇒ symfony console make:migration
[WARNING] No database changes were detected.
The database schema and the application mapping information are already in sync.
Can someone help me? If I didn't understand how it works or something else...
Thank!

I had the same issue. Clearing the cache worked for me.
symfony console cache:clear

Related

Copy Paste entities from a project to another symfony

I have a projet that includes many entities and their controller and crud, etc
I want to reuse them in another projet. So I want to copy paste the files.
But I already have a problem at entity creation:
The cmd shows that make: entity creates the entity class and the repository class (and nothing else) .So I copy paste these two to the new projet but they are ignored:
When I try make:migration, I got No database changes were detected. When I try make:entity and type the name of the entity class (Taxe), I got _Cannot find the entity manager for class "App\Entity\Taxe" . and make:controller with Taxe as entity return _ Entity "Taxe" doesn't exist; .
So globally, how to create entity without the maker ? How can I reuse my entities/controllers/etc from another project pls?
Globally, to reuse your controllers/entities, just copy/paste them in the right folder.
Entities : src/Entity
Controllers : src/Controller
Repositories: src/Repository
After that (if your database is created, else run php bin/console doctrine:database:create) , you can make php bin/console make:migration and php bin/console doctrine:migrations:migrate to apply changements.
The cmd shows that make: entity creates the entity class and the repository class (and nothing else)
If you want to generate templates, you have to run php bin/console make:controller, name your controller and controller file + template will be generated (this implies that your project is a web app and not an api).

In Symfony 5, the command doctrine:database:create outputs an error instead of creating a database for test environment

I'm learning Symfony 5 at Symfony 5: The Fast Track and I'm at the step 17.4 Working with a Test Database.
I can read from the beginning of this section:
... the Symfony CLI automatically exposes the DATABASE_URL
environment variable. When APP_ENV is test, like set when running
PHPUnit, it changes the database name from main to main_test so
that tests have their very own database.
Before being able to run the test, we need to “initialize” the test
database (create the database and migrate it):
$ APP_ENV=test symfony console doctrine:database:create
$ APP_ENV=test symfony console doctrine:migrations:migrate -n
My database name is guestbook, running under MySql & Apache, as specified in the .env file:
DATABASE_URL="mysql://root:#127.0.0.1:3306/guestbook?serverVersion=mariadb-10.4.19"
So, while I was expecting a database named guestbook_test to be created when I execute the command symfony console doctrine:database:create, it outputs the following error:
Could not create database `guestbook` for connection named default
An exception occurred while executing 'CREATE DATABASE `guestbook`':
SQLSTATE[HY000]: General error: 1007 Can't create database 'guestbook'; database exists
exit status 1
To make sure the environment is "test", I, first, tried these two ways:
In the .env file: APP_ENV=test
In the .env.local file: APP_ENV=test
But, I got the same error.
When I displayed the content of environment variable APP_ENV from a controller, using return new Response("APP_ENV = '" . getenv('APP_ENV') . "'");, it displays a null value: APP_ENV=''.
So, I assigned the value 'test' to APP_ENV in Real environment variables (for me, that was Windows/Paramaters/environment variables...etc). This once, the controller displays APP_ENV='test', but I get always the same error, when I execute the Doctrine command: symfony console doctrine:database:create
I don't know what I'm missing !! Please, any help?
UPDATE ON: 07 June 2021 22:05
I, even tried assigning the value test to APP_ENV in php.ini; but, when I displayed this env var using: symfony console debug:container --env-var=APP_ENV, I got:
Symfony Container Environment Variables
=======================================
// Displaying detailed environment variable usage matching APP_ENV
None of the environment variables match this name.
It's, little bit, strange since I have this env var assigned every where (in .env file, .env.local, php.ini and in a real env vars) and this command says there is no env var called APP_ENV !
What helped in my case:
create .env.local file
copy the DATABASE_URL variable with db name suffixed with _test
I also had to change db user to root, as my app db user didn't have permissions to create databases,

generate initial migration after creating entity and repository for an existing database

After creating an Entity and Repository from an existing pre-doctrine database, I am unable to make an initial migration. It gave me this error [ERROR] The version "latest" couldn't be reached, there are no registered migrations. Any idea how to do an initial migration without starting fresh? And for some reason, the migration folder exists outside the src folder, why is it so? In a previous project, the migration folder exists inside the src folder.
Any insight would be appreciated. Thank you for reading.
EDIT: doctrine_migrations.yaml:
doctrine_migrations:
migrations_paths:
# namespace is arbitrary but should be different from App\Migrations
# as migrations classes should NOT be autoloaded
'DoctrineMigrations': '%kernel.project_dir%/migrations'
The commands I used to generate the Entity and its Repository is as follows:
php bin/console doctrine:mapping:import "App\Entity" annotation --path=src/Entity
modified the #ORM\Entity => #ORM\Entity(repositoryClass="App\Repository\UserRepository") in the entity .php
php bin/console make:entity --regenerate
Then when I run bin/console doctrine:migrations:migrate, the error pops up.
Work for me
doctrine_migrations:
migrations_paths:
'App\Migrations': '%kernel.project_dir%/src/Migrations'
and use for migration classes
namespace App\Migrations;
THis is my migrations config.You can test it :
doctrine_migrations:
dir_name: '%kernel.project_dir%/src/Migrations'
# namespace is arbitrary but should be different from App\Migrations
# as migrations classes should NOT be autoloaded
namespace: DoctrineMigrations
For migration commande i use : php bin/console d:m:diff and after this you can use the migration number with this commande :
php bin/console d:m:e --up the_migration_number
I tried most of the methods but it seems that it is possible to generate the migration. However, changes to the entity will not be detected by doctrine.
For example, if I change the field of name to username, php bin/console doctrine:migration:diff does not detect the changes.
What I found worked was exporting the database as .sql, creating the entity the normal way, and manually typing in the fields. Delete the generated table in phpmyadmin, and importing the data back in. Only then would it be working as I want it to be.

database error on schema validate with Doctrine

I'm attempting to create a database using the doctrine orm with an application built by someone else. I'm getting Database errors, and I'm unsure if I'm unclear on the concept, or if I need to adjust the Annotations.
Command and output:
php bin/console doctrine:schema:validate
Mapping
-------
[OK] The mapping files are correct.
Database
--------
15:06:28 ERROR [console] Error thrown while running command "doctrine:schema:validate". Message: "Invalid index-name unique_organization_id_application_id given, has to be [a-zA-Z0-9_]" ["error" => Doctrine\DBAL\Schema\SchemaException { …},"command" => "doctrine:schema:validate","message" => "Invalid index-name unique_organization_id_application_id given, has to be [a-zA-Z0-9_]"] []
[Doctrine\DBAL\Schema\SchemaException]
Invalid index-name unique_organization_id_application_id given, has to be [a-zA-Z0-9_]
It almost sounds like the database isn't set up properly(though I thought this was the first step before setting up the database schema)
The annotation:
#ORM\Table(name="applications", uniqueConstraints={#UniqueConstraint(name="unique_organization_id_application_id", columns={"organization_id", "application_id"})})
And this is where I'm out of my depth. organizationId and applicationId are both private members(?) of the class, with getters and setters. unique_organization_id_application_id isn't found anywhere in the class.
Invalid index-name unique_organization_id_application_id given, has to be [a-zA-Z0-9_]
The error says that you inserted some non-english letters in the index name. Try to completly remove the name.

Symfony2 generate entities error

I'm trying to generate entities from existing tables in database, I keep getting the same error in a particular entity, which is imported from a second database (or entity manager), but I re-created this table in main database to use the same entity manager and get the same error, so I'm lost about what is happening.
This are my commands to generate it:
php app/console doctrine:mapping:convert yml ./src/MyShop/ProductBundle/Resources/config/doctrine/metadata/orm --from-database --filter="Product" --em=mysecondaryem
(BTW, is there a way to force exact filter? I only need Product)
Which seems to be ok:
Processing entity "ProductSold"
Processing entity "Product"
Exporting "yml" mapping information to...
Then
php app/console doctrine:mapping:import MyShopProductBundle annotation --em=mysecondaryem
Which is weird, as it is logging information about all other tables existing in this db but it's only generating the corresponding to "Product" as filtered (only the files ProductSold.php and Product.php do really exist):
Importing mapping information from "mysecondaryem" entity manager
> writing C:\mysite\src\MyShop\ProductBundle/Entity/ProductSold.php
> writing C:\mysite\src\MyShop\ProductBundle/Entity/Family.php
> writing C:\mysite\src\MyShop\ProductBundle/Entity/Category.php
> writing C:\mysite\src\MyShop\ProductBundle/Entity/Item.php
> writing C:\mysite\src\MyShop\ProductBundle/Entity/Stock.php
> writing C:\mysite\src\MyShop\ProductBundle/Entity/Product.php
Then, in the third step, I get an error:
php app/console doctrine:generate:entities MyShopProductBundle --no-backup
Generating entities for bundle "MyShopProductBundle"
[RuntimeException]
Bundle "MyShopProductBundle" does not contain any mapped entities.
doctrine:generate:entities [--path="..."] [--no-backup] name
As I sayed, I tried omitting secondary entity manager (replicating tables in my first database) and I get the same error.
You've verified that C:\mysite\src\MyShop\ProductBundle/Entity/Product.php has been created, but have you also checked that it actually contains mapped entities ?
Ok, I found the error, I was missing --force parameter, first step command should be:
php app/console doctrine:mapping:convert yml ./src/MyShop/ProductBundle/Resources/config/doctrine/metadata/orm --from-database --force --filter="Product" --em=mysecondaryem

Resources