Symfony 4.1 - Two EntityManagers. Migration goes twice on second EntityManager - symfony

I've followed the directions on this page:
https://symfony.com/doc/current/doctrine/multiple_entity_managers.html
And my doctrine.yaml file looks like:
doctrine:
dbal:
default_connection: one
connections:
one:
# configure these for your database server
url: '%env(DATABASE_ONE_URL)%'
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
two:
# configure these for your database server
url: '%env(DATABASE_TWO_URL)%'
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
orm:
default_entity_manager: one
entity_managers:
one:
connection: one
mappings:
One:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity/One'
prefix: 'App\Entity\One'
alias: One
two:
connection: two
mappings:
Two:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity/Two'
prefix: 'App\Entity\Two'
alias: Two
I've got a One and Two directory inside my Entity directory with a simple Entity class in both:
A Person in One:
<?php
namespace App\Entity\One;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="person")
*/
class Person
{
/**
* #var int
*
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $name;
{Getters and setters ...}
}
A Post in Two:
<?php
namespace App\Entity\Two;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="post")
*/
class Post
{
/**
* #var int
*
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $title;
{Getters and setters ...}
}
When I run bin/console doctrine:migrations:diff and bin/console doctrine:migrations:migrate the Person is added to the One database correctly.
When I run bin/console doctrine:migrations:diff --em=two and bin/console doctrine:migrations:migrate --em=two both this and the Person migration for One are executed and the Two database has both a Person and a Page table.
I can't seem to figure out where I'm going wrong with this

Related

FOSUserBundle + JMSSerializerBundle + exposing extra fields

I have an issue when serializing a User instance with one additional field $name, which extends the base User from FOSUserBundle:
<?php
namespace AppBundle\Entity\User;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
/**
* User
*/
class User extends BaseUser
{
/**
* #var string
*/
private $name;
/**
* Set name
* #param string $name
* #return User
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
* #return string
*/
public function getName()
{
return $this->name;
}
}
To simplify, I need to expose only $salt field from User entity using JMSSerializerBundle
#AppBundle\Resources\config\serializer\Model.User.yml
FOS\UserBundle\Model\User:
exclusion_policy: all
properties:
salt:
expose: true
Here's the config for it:
#app\config\config.yml
jms_serializer:
metadata:
auto_detection: true
directories:
FOSUserBundle:
namespace_prefix: "FOS\\UserBundle"
path: "#AppBundle/Resources/config/serializer"
The issue is that the serializer exposes also $name field, which I don't want as I need only to have $salt exposed:
{
"salt": "abcdefg",
"name": "Admin"
}
I believe I need to tell the serializer to use a config for my AppBundle\Entity\User instead of the base user entity from FOSUserBundle, but I have no clue how to implement it.
This is how I solved the issue . I have a User.php class that
inherit from FOS\UserBundle\Model\User as BaseUser. I need control the serialization from both my BaseUser class and my User class.
Solution: you need 2 separated config file to control each class.
config.yml
#Serializer configuration
jms_serializer:
metadata:
directories:
AppBundle:
path: "#AppBundle/Resources/config/serializer"
FOSUB:
namespace_prefix: "FOS\\UserBundle"
path: "%kernel.root_dir%/serializer/FOSUB"
Model.User.yml
FOS\UserBundle\Model\User:
exclusion_policy: ALL
properties:
id:
expose: true
username:
expose: true
email:
expose: true
enabled:
expose: true
Entity.User.yml
AppBundle\Entity\User:
exclusion_policy: ALL
properties:
imageAvatar:
expose: true
updatedAt:
expose: true
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*
* #ORM\Table(name="usuario")
* #ORM\Entity(repositoryClass="DietaBundle\Repository\UserRepository")
*
*
*/
class User extends BaseUser
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*
* #var string
*/
private $imageAvatar;
/**
* #ORM\Column(type="datetime")
*
* #var \DateTime
*/
private $updatedAt;
Clear the cache after each change in the configuration files.
cache:clear
It happens because you are using the exclusion_policy: all on the parent entity, instead of on the child entity, which still exposing all of it's properties.
you should switch to your bundle in the configuration (config.yml) under the jms_seriazlier:directories.
any-name:
namespace_prefix: "My\\FooBundle"
path: "#MyFooBundle/Resources/config/serializer"
now you could use the same configuration to expose only the desired property.
#AppBundle\Resources\config\serializer\Entity.User.yml
My\FooBundle\Entity\User:
exclusion_policy: all
properties:
salt:
expose: true

Symfony2 - translatable field - The class 'Gedmo\Translatable\Entity\Translation' was not found in the chain configured namespaces

I'm trying to translate some fields of my entity and I have the following error when I'm try create an object...
<?php
namespace XXXX\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Translatable\Translatable;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Line
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="XXXX\Entity\LineRepository")
*/
class Line implements Translatable
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #Gedmo\Translatable
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Line
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
public function setTranslatableLocale($locale)
{
$this->locale = $locale;
}
}
And the error:
[Doctrine\Common\Persistence\Mapping\MappingException]
The class 'Gedmo\Translatable\Entity\Translation' was not found in the chain configured namespaces
I'm using Symfony 2.5, but in 2.4 occurs too. Any idea how I can solve this?
You need to configure the translatable Entity to use as well. In config.yml:
orm:
(....)
mappings:
translatable:
type: annotation
is_bundle: false
prefix: Gedmo\Translatable\Entity
dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Translatable/Entity"
alias: GedmoTranslatable
Update for Symfony 5 :
Configure the /config/packages/doctrine.yaml file and add the following
orm:
(....)
mappings:
translatable:
type: annotation
is_bundle: false
prefix: Gedmo\Translatable\Entity
dir: '%kernel.project_dir%/vendor/gedmo/doctrine-extensions/src/Translatable/Entity'
alias: GedmoTranslatable

can't generate table for entity OryzoneMediaStorageBundle symfony2

this my entity class
<?php
namespace Application\MainAppBundleBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Oryzone\Bundle\MediaStorageBundle\Entity\Media as BaseMedia;
/**
Application\MainAppBundleBundle\Entity\Media *
#ORM\Table(name="media")
#ORM\Entity() */
class Media extends BaseMedia
{
/**
* #ORM\Id
* #ORM\Column(name="id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* {#inheritDoc}
*/
public function getId()
{
return $this->id;
}
}
?>
when i execute "php app/console doctrine:update:schema --force" i get this message
nothing to update ...
help please
Resolved ✔
the problem: when I execute doctrine:schema:update, the update of the data base is based on the files in # MyBundle / Resources / config / doctrine / MyFiles.orm.yml since I created my entity Entity / media.php and I have not Media.orm.yml the media table will not be created, so I deleted all files * orm.yml and I execute php app / console doctrine.: schema: update and the table is created
#hourss2040
I think you can't combine .orm.yml and annotations in same Entity.
Try to switch auto mapping on like this:
doctrine:
orm:
auto_mapping: true
Or register your bundle mapping like this:
doctrine:
orm:
entity_managers:
default:
connection: default
mappings:
MainAppBundleBundle: ~

Doctrine Behaviors fields in Symfony2 auto-generated CRUD

I'm starting with Symfony and I have Entity "Post"
<?php
namespace My\BackendBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Post
*
* #ORM\Table()
* #ORM\Entity
*/
class Post
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #Gedmo\Slug(fields={"title"})
* #ORM\Column(type="string", length=255, unique=true)
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="text", type="text")
*/
private $text;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Post
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set text
*
* #param string $text
* #return Post
*/
public function setText($text)
{
$this->text = $text;
return $this;
}
/**
* Get text
*
* #return string
*/
public function getText()
{
return $this->text;
}
/**
* Set slug
*
* #param string $slug
* #return Post
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
}
I've generated table in database:
app/console doctrine:schema:update --force
And CRUD panel:
app/console doctrine:generate:crud
with options:
Entity: MyBackendBundle:Post
"write" action: yes
But as you can see, I have "slug" field and I want Doctrine to auto-generate it. But default CRUD panel at "/post/new" have inputs for all 3 fields (title, slug and text). And after hours of searching for solution only one I can do is manually delete "slug" input from My/BackendBundle/Form/PostType.php.
I don't know if I'm doing something wrong or it's just works like that? Sluggable behavior works good when I'm adding entity manually (by creating new Post() with title and text and doing $manager->flush()).
My /app/config/config.yml file:
imports:
- { resource: parameters.yml }
- { resource: security.yml }
framework:
#esi: ~
translator: { fallback: %locale% }
secret: %secret%
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
templating:
engines: ['twig']
#assets_version: SomeVersionScheme
default_locale: "%locale%"
trusted_proxies: ~
session: ~
fragments: ~
# Twig Configuration
twig:
debug: %kernel.debug%
strict_variables: %kernel.debug%
# Assetic Configuration
assetic:
debug: %kernel.debug%
use_controller: false
bundles: [ ]
#java: /usr/bin/java
filters:
cssrewrite: ~
#closure:
# jar: %kernel.root_dir%/Resources/java/compiler.jar
#yui_css:
# jar: %kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar
# Doctrine Configuration
doctrine:
dbal:
driver: %database_driver%
host: %database_host%
port: %database_port%
dbname: %database_name%
user: %database_user%
password: %database_password%
charset: UTF8
# if using pdo_sqlite as your database driver, add the path in parameters.yml
# e.g. database_path: %kernel.root_dir%/data/data.db3
# path: %database_path%
orm:
auto_generate_proxy_classes: %kernel.debug%
auto_mapping: true
mappings:
StofDoctrineExtensionsBundle: false
stof_doctrine_extensions:
default_locale: en_US
orm:
default:
sluggable: true
# Swiftmailer Configuration
swiftmailer:
transport: %mailer_transport%
host: %mailer_host%
username: %mailer_user%
password: %mailer_password%
spool: { type: memory }
fos_user:
db_driver: orm
firewall_name: main
user_class: My\UserBundle\Entity\User
If it's normal and I have to do it manually simple confirmation would be great.
app/console doctrine:generate:crud command use generate:doctrine:form command which generate fields for all entity properties.
So yes, you must remove unnecessary fields from form OR use more advenced generators like AdmigeneratorGeneratorBundle.

Fatal Error when installing stof bundle and doctrine extensions (tree)

Here is the problem : I don't succeed to install stof bundle with symphony 2.0
How I proceed :
I add this lines in deps file :
[GedmoDoctrineExtensions]
git=https://github.com/l3pp4rd/DoctrineExtensions.git
target=bundles/gedmo-doctrine-extensions
version=e93fc1e0a0
[StofDoctrineExtensionsBundle]
git=https://github.com/stof/StofDoctrineExtensionsBundle.git
target=bundles/Stof/DoctrineExtensions/Bundle
version=6b2a8c74bd
Then I run the command
php bin/vendors install --reinstall
All is fine.
Then I activate extensions in concerned files
# config.yml
stof_doctrine_extensions:
default_locale: en_US
orm:
default:
tree: true
orm:
auto_generate_proxy_classes: %kernel.debug%
auto_mapping: true
mappings:
StofDoctrineExtensionsBundle: ~
# AppKernel.php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
[...]
new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
[...]
);
# autoload.php
use Symfony\Component\ClassLoader\UniversalClassLoader;
use Doctrine\Common\Annotations\AnnotationRegistry;
$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
'Gedmo' => __DIR__.'/../vendor/gedmo-doctrine-extensions/lib',
'Stof' => __DIR__.'/../vendor/bundles',
[...]
));
At last, I add my entity Category, as in this tutorial http://gediminasm.org/article/tree-nestedset-behavior-extension-for-doctrine-2#including-extension
<?php
namespace Myproject\MyBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* #Gedmo\Tree(type="nested")
* #ORM\Table(name="Category")
* use repository for handy tree functions
* #ORM\Entity(repositoryClass="Gedmo\Tree\Entity\Repository\NestedTreeRepository")
*/
class Category
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue
*/
private $id;
/**
* #ORM\Column(name="title", type="string", length=64)
*/
private $title;
/**
* #Gedmo\TreeLeft
* #ORM\Column(name="lft", type="integer")
*/
private $lft;
/**
* #Gedmo\TreeLevel
* #ORM\Column(name="lvl", type="integer")
*/
private $lvl;
/**
* #Gedmo\TreeRight
* #ORM\Column(name="rgt", type="integer")
*/
private $rgt;
/**
* #Gedmo\TreeRoot
* #ORM\Column(name="root", type="integer", nullable=true)
*/
private $root;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="SET NULL")
*/
private $parent;
/**
* #ORM\OneToMany(targetEntity="Category", mappedBy="parent")
* #ORM\OrderBy({"lft" = "ASC"})
*/
private $children;
}
But when I run the command php app/console generate:doctrine:entities MyProjectMyBundle:Category, I have the following error :
Fatal error: Out of memory (allocated -1227096064) (tried to allocate 261900 bytes) in /home/user/Project/vendor/doctrine/lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php on line 75
And sometimes this one :
Fatal error: Out of memory (allocated -1222901760) (tried to allocate 261900 bytes) in /home/user/Project/vendor/gedmo-doctrine-extensions/lib/Gedmo/Mapping/MappedEventSubscriber.php on line 176
What do I do wrong ?
I would say that these errors have nothing to do with Symfony nor Doctrine. To me it's more like a PHP configuration issue.
You can try to increase the memory_limit value in your php.ini file. A memory limit of 128MB should suffice in most cases but if your project is handling a lot of data it may need more.
Try to load only the tree extention:
doctrine:
orm:
entity_managers:
default:
mappings:
gedmo_tree:
type: annotation
prefix: Gedmo\Tree\Entity
dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Tree/Entity"
alias: GedmoTree # this one is optional and will default to the name set for the mapping
is_bundle: false
As the documentation says: https://github.com/stof/StofDoctrineExtensionsBundle/blob/master/Resources/doc/index.rst#add-the-extensions-to-your-mapping

Resources