can't update database symfony 4 with sonataClassificationBundle - symfony

im using Symfony 4.1
When you install SonataMediaBundle and SonataClassificationBundle after configure the both of them.
and you want execute the commande
php bin/console doctrine:schema:update --force
you got this Error
The table with name 'shop.classification__collection' already exists.
same for all other table of classification like category and tag
if you try to change the name of table in the entity of classification__collection to classification_collection
you will get a second error like
An exception occurred while executing 'CREATE UNIQUE INDEX tag_collection ON classification__collection (slug, context):
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

I run in this problem recently and find the solution.
The issue is address here
https://github.com/sonata-project/SonataClassificationBundle/issues/407
You just need to remove the entity created in App/Entity by classification or remapped the class to the App/Entity in sonata.yaml and sonata_classification.yaml
If you deleted the entities in App/Entity add the following cofiguration to your sonata.yaml and sonata_classification.yaml
/** sonata_classification.yaml**/
sonata_classification:
class:
tag: App\Application\Sonata\ClassificationBundle\Entity\Tag
category: App\Application\Sonata\ClassificationBundle\Entity\Category
media: App\Application\Sonata\MediaBundle\Entity\Media
collection: App\Application\Sonata\ClassificationBundle\Entity\Collection
context: App\Application\Sonata\ClassificationBundle\Entity\Context
/** sonata.yaml**/
class:
media: App\Application\Sonata\MediaBundle\Entity\Media
gallery: App\Application\Sonata\MediaBundle\Entity\Gallery
gallery_has_media: App\Application\Sonata\MediaBundle\Entity\GalleryHasMedia
category: App\Application\Sonata\ClassificationBundle\Entity\Category

Related

Elasticsearch with symfony - Error populate command softdeletable entity

I use the symfony bundle Foselasticabundle and i am facing a problem.
I have an entity (B) which can be deleted via gedmo softdeleteable.
I created the mapping, via the YAML file, and when I execute the following command fos:elastica:populate i get an error.
Entity of type 'App\Entity\B' for IDs id(XX) was not found
In fact, value was previously deleted in my database...
I would have liked him to insert an empty value in the field
Do you have a solution?
Thank you for your answers
fos_elastica.yaml
clients:
default: { url: '%env(ELASTICSEARCH_URL)%/' }
indexes:
app:
types:
A:
properties:
id: ~
name: ~
B:
type: object
id: ~
persistence:
driver: orm
model: App\Entity\A

Laravel 5.7 artisan migrate

I installed recently laravel 5.7. How to fix error "php artisan migrate"?
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))
at C:\laravel\blg2\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error 661| // message to include the bindings with SQL, which will make this exception a 662| // lot more helpful to the developer instead of just the database's errors. 663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Exception trace:
1 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes") C:\laravel\blg2\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458
2 PDOStatement::execute()
C:\laravel\blg2\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458
Please use the argument -v to see more details.
Thank you
Laravel uses the utf8mb4 character set by default, which includes support for storing "emojis" in the database. If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them.
Inside your AppServiceProvider:
use Illuminate\Support\Facades\Schema;
...
public function boot()
{
Schema::defaultStringLength(191);
}
Alternatively, you may enable the innodb_large_prefix option for your database. Refer to your database's documentation for instructions on how to properly enable this option.
For more information about indexes: https://laravel.com/docs/5.7/migrations#indexes
If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them.
You can have it fixed as Chin Leung said.
Or adding the length of the record directly in the migration.
$table->string('email', 100); VARCHAR equivalent column with a optional length.
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50);
$table->string('email', 90)->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
On xampp php 7.3.2, laravel 5.7 & also in laravel 5.8.3 it happened to me. Only changed the config/database.php file.
config/database.php
Changed charset & collation on mysql & it worked fine. Change this part
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
as
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
Now it will accept the long keys.
You need to go to
App\Providers\AppServiceProvider.php
Now Add the following code and then save and run php artisan serve
use Illuminate\Support\Facades\Schema;
...
public function boot()
{
Schema::defaultStringLength(191);
}
I use Laravel 5.7 but this error always comes up. ADD this code in every project. Also try to use Laravel with php7+ so that it doesnot show you PDO::Exception Error...
Open your AppServiceProvider.php, Path >> App\Providers\AppServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
**use Illuminate\Support\Facades\Schema;**
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
**Schema::defaultStringLength(191);**
}
You can define the string length as well to solve this kind of error
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name',20);
$table->string('email',80)->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password',8);
$table->rememberToken();
$table->timestamps();
});

Can not delete User with FOSOAuthBundle enabled

I try to delete a user in my symfony 3 app. I use the FOSOAuthBundle and the FOSUserBundle.
I tried this code:
$em = $this->getDoctrine()->getManager();
$em->remove($user);
$em->flush();
But I get this error:
An exception occurred while executing 'DELETE FROM user WHERE id = ?' with params [1]:\n\nSQLSTATE[23000]:
Integrity constraint violation: 1451 Cannot delete or update a parent row:
a foreign key constraint fails (`database`.`access_token`, CONSTRAINT `FK_B6A2DD68A76ED395` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`))
I have this configuration:
# FOSOAuthServerBundle configuration
fos_oauth_server:
db_driver: orm
client_class: OAuthBundle\Entity\Client
access_token_class: OAuthBundle\Entity\AccessToken
refresh_token_class: OAuthBundle\Entity\RefreshToken
auth_code_class: OAuthBundle\Entity\AuthCode
service:
user_provider: fos_user.user_provider.username_email
options:
access_token_lifetime: 86400
refresh_token_lifetime: 2.628e+6
If I get a access token the user field is always null though in the database the correct id is saved and it is possible to login with this token.
YOu need to configure cascade operations. You need to decide what do you want to happen on access_token table when you delete an user. You can delete de token or set the related user as null.
More info here

Symfony - can't get multiple file upload to work

I'm using VichUploaderBundle to upload files for a gallery. I have two entities - the first one is Gallery, and the second is GalleryImage.
THis is the code:
http://pastebin.com/2nWAK2iH - Gallery Entity
http://pastebin.com/JWzWzZp2 - GalleryImage Entity
http://pastebin.com/TnZr24Sp - GalleryImageType Form
http://pastebin.com/9C8H25sn - GalleryType Form
http://tny.cz/26e859f6 - The Controller (part of it)
No matter what I do, I always get
"An exception occurred while executing 'INSERT INTO GalleryImage (image_name, gallery_id) VALUES (?, ?)' with params [null, 8]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'image_name' cannot be null"
Any ideas what I'm doing wrong?
Thanks
UPDATE
The new GalleryImage file: http://pastebin.com/uKtqg4HE
Looks like the #Uploadable class annotation is missing in the GalleryImage class.

How to generate entities from database view with doctrine and symfony2

I am trying to generate entities from database using standard console commands as described in Symfony2 documentation here: http://symfony.com/doc/current/cookbook/doctrine/reverse_engineering.html.
php app/console doctrine:mapping:convert --from-database --force yml "src/My/HomeBundle/Resources/config/doctrine/metadata/orm"
php app/console doctrine:mapping:import MyHomeBundle yml
php app/console doctrine:generate:entities MyHomeBundle
After this, all tables are generated correctly. The problem is that this won't generate entities for database views. When I add yml files myself into src/My/HomeBundle/Resources/config/doctrine/metadata/orm for example:
UserInGroup:
type: entity
table: user_in_group_view
fields:
id:
id: true
type: integer
unsigned: false
nullable: false
generator:
strategy: IDENTITY
userId:
type: integer
unsigned: false
nullable: false
column: user_id
userGroupId:
type: integer
unsigned: false
nullable: false
column: user_group_id
lifecycleCallbacks: { }
I get this exception when running php app/console doctrine:generate:entities MyHomeBundle:
Notice: Undefined index: My\HomeBundle\Entity\UserInGroup in C:\Users\ThisIsMe\Projects\SymfonyTestProject\vendor\doctrine\lib\Doctrine\ORM\Mapping\Driver\AbstractFileDriver.php line 121
Similar question was posted here: How to set up entity (doctrine) for database view in Symfony 2
I know I can create Entity class, but I was hoping that I could get this generated so if I change my view, I could just regenerate entity classes. Any suggestions?
Now you create your orm files only. You need to follow 2 more steps. I will give you the complete steps from begining.
Before doing this delete all yml files in your orm directory that you had created early.
I hope MyHomeBundle is your bundle name
1).php app/console doctrine:mapping:convert yml ./src/My/HomeBundle/Resources/config/doctrine --from-database --force
Symfony2 generate entity from Database
2).php app/console doctrine:mapping:import MyHomeBundle yml
3).php app/console doctrine:generate:entities MyHomeBundle
Hope this helps you.
Got the same issue, i use xml instead of yml but must be the same.
Check in your orm entity if the name include the correct route, exemple:
<entity name="Myapp\MyrBundle\Entity\MyEntity" table="myentity">
Because when i generate my orm from database the name was like that:
<entity name="MyEntity" table="myentity">
So doctrine didn't understand the right path.
Hope i'm clear and this will help you!
I know it's an old question but I found the trick (Symfony 6) to generate entities from SQL view (I use a SQL server database).
So I modified two methods of the SQLServerPlatform.php file of the doctrine bundle.
public function getListTablesSQL()
{
// "sysdiagrams" table must be ignored as it's internal SQL Server table for Database Diagrams
// Category 2 must be ignored as it is "MS SQL Server 'pseudo-system' object[s]" for replication
return 'SELECT name, SCHEMA_NAME (uid) AS schema_name FROM sysobjects'
. " WHERE type = 'V' AND name != 'sysdiagrams' AND category != 2 ORDER BY name";
}
I changed the where condition parameter 'U' by 'V' for view.
Same operation for the method getListTableColumnsSQL(), we change here the 'U' parameter of the where condition by 'V'.
public function getListTableColumnsSQL($table, $database = null)
{
return "SELECT col.name,
type.name AS type,
col.max_length AS length,
~col.is_nullable AS notnull,
def.definition AS [default],
col.scale,
col.precision,
col.is_identity AS autoincrement,
col.collation_name AS collation,
CAST(prop.value AS NVARCHAR(MAX)) AS comment -- CAST avoids driver error for sql_variant type
FROM sys.columns AS col
JOIN sys.types AS type
ON col.user_type_id = type.user_type_id
JOIN sys.objects AS obj
ON col.object_id = obj.object_id
JOIN sys.schemas AS scm
ON obj.schema_id = scm.schema_id
LEFT JOIN sys.default_constraints def
ON col.default_object_id = def.object_id
AND col.object_id = def.parent_object_id
LEFT JOIN sys.extended_properties AS prop
ON obj.object_id = prop.major_id
AND col.column_id = prop.minor_id
AND prop.name = 'MS_Description'
WHERE obj.type = 'V'
AND " . $this->getTableWhereClause($table, 'scm.name', 'obj.name');
}
Maybe this will help someone.
As you can see here:
http://symfony.com/doc/current/cookbook/doctrine/reverse_engineering.html
the reverse engineering process from db to entity is not fully implemented yet:
"As the Doctrine tools documentation says, reverse engineering is a one-time process to get started on a project. Doctrine is able to convert approximately 70-80% of the necessary mapping information based on fields, indexes and foreign key constraints. Doctrine can't discover inverse associations, inheritance types, entities with foreign keys as primary keys or semantical operations on associations such as cascade or lifecycle events. Some additional work on the generated entities will be necessary afterwards to design each to fit your domain model specificities."

Resources