I want to use the sql function MD5 in my Symfony bundle so I added the file (https://gist.github.com/Basster/2774738) in \MyCompany\MyBundle\DQL\MD5Function.
Then I changed my config.yml file :
# app/config/config.yml
doctrine:
orm:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Added configuration for MD5 function
entity_managers:
default:
dql:
string_functions:
MD5: MyCompany\MyBundle\DQL\MD5Function
But I have the following error :
InvalidConfigurationException in ArrayNode.php line 309: Unrecognized options "naming_strategy, auto_mapping" under "doctrine.orm"
You mix the one entity manager configuration and the multi entity manager one.
You should use:
# app/config/config.yml
doctrine:
orm:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Added configuration for MD5 function
dql:
string_functions:
MD5: MyCompany\MyBundle\DQL\MD5Function
or:
# app/config/config.yml
doctrine:
orm:
entity_managers:
default:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Added configuration for MD5 function
dql:
string_functions:
MD5: MyCompany\MyBundle\DQL\MD5Function
Alternatively you can create your own class to do that like explained here How to create and use custom built doctrine DQL function in symfony. Funny enough the example is based on SHA1 so you can just simply change the SH1 to MD5, like I did below.
Your custom MD5 class
namespace Football\FrontendBundle\DQL;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
class Md5 extends FunctionNode
{
public $value;
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->value = $parser->StringPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql(SqlWalker $sqlWalker)
{
return 'MD5(' . $this->value->dispatch($sqlWalker) . ')';
}
}
Register it in config.yml
doctrine:
orm:
dql:
string_functions:
MD5: Football\FrontendBundle\DQL\Md5
And use it in your repository like this
namespace Football\FrontendBundle\Repository;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query;
class CountryRepository extends EntityRepository
{
public function findOneCountryBy($id)
{
return
$this
->createQueryBuilder('c')
->select('c, MD5(c.code) AS code')
->where('c.id = :id')
->setParameter('id', $id)
->getQuery()
->getSingleResult(Query::HYDRATE_SCALAR);
}
}
Related
I have the following Doctrine entities where EntityA is the owning side:
<?php
class EntityA
{
/**
* #ORM\ManyToOne(targetEntity="EntityB" , inversedBy="propertyA")
*/
private $propertyB;
// ....
public function setEntityB(EntityB $entBRef)
{
$this->propertyB = $entBRef;
}
}
class EntityB
{
/**
* #ORM\OneToMany(targetEntity="EntityA", mappedBy="propertyB")
*/
private $propertyA;
// ....
}
I do also have a RepositoryB class:
<?php
class RepositoryB extends \Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository
{
public function __construct(\Doctrine\Common\Persistence\ManagerRegistry $registry)
{
parent::__construct($registry, EntityB::class);
}
}
Then in my class I am trying to persist an EntityA object:
<?php
class SomeService
{
/** #var RepositoryB */
private $repositoryB;
/** #var EntityManagerInterface */
private $entityManager;
public function __construct(RepositoryB $repositoryB, EntityManagerInterface $entityManager)
{
$this->repositoryB = $repositoryB;
$this->entityManager = $entityManager;
}
public function testSomething()
{
$entBRef = $this->repositoryB->find(1);
$newEnt = (new EntityA());
$newEnt->setEntityB($entBRef);
$this->entityManager->persist($newEnt);
$this->flush();
}
}
But I've got the following error:
A new entity was found through the relationship 'EntityA#propertyB'
that was not configured to cascade persist operations for entity:
EntityB. To solve this issue: Either explicitly call
EntityManager#persist() on this unknown entity or configure cascade
Here is how my doctrine.yaml file looks like:
parameters:
env(DATABASE_URL_WRITE): ''
services:
gedmo.listener.timestampable:
class: Org\CompBundle\Gedmo\Timestampable\TimestampableListener
tags:
- { name: doctrine.event_subscriber, connection: default }
calls:
- [ setAnnotationReader, [ "#annotation_reader" ] ]
gedmo.listener.loggable:
class: Gedmo\Loggable\LoggableListener
tags:
- { name: doctrine.event_subscriber, connection: default }
calls:
- [ setAnnotationReader, [ "#annotation_reader" ] ]
gedmo.listener.deleteable:
class: Gedmo\SoftDeleteable\SoftDeleteableListener
tags:
- { name: doctrine.event_subscriber, connection: default }
calls:
- [ setAnnotationReader, [ '#annotation_reader' ] ]
doctrine:
dbal:
default_connection: default
types:
microseconds: Org\CompBundle\DBAL\Types\DateTimeMicrosecondsType
connections:
read_only:
url: '%env(resolve:DATABASE_URL_READ)%'
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
default_table_options:
charset: utf8mb4
collate: utf8mb4_unicode_ci
default:
url: '%env(resolve:DATABASE_URL_WRITE)%'
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
default_table_options:
charset: utf8mb4
collate: utf8mb4_unicode_ci
orm:
auto_generate_proxy_classes: '%kernel.debug%'
default_entity_manager: default
entity_managers:
filters:
filters:
softdeleteable:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
enabled: true
read_only:
connection: read_only
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
mappings:
gedmo_loggable:
type: annotation
prefix: Gedmo\Loggable\Entity
dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Loggable/Entity"
alias: GedmoLoggable
is_bundle: false
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/vendor/org/comp-bundle/Entity'
prefix: 'Org\CompBundle\Entity'
alias: Drm
dql:
datetime_functions:
timetosec: DoctrineExtensions\Query\Mysql\TimeToSec
timediff: DoctrineExtensions\Query\Mysql\TimeDiff
now: DoctrineExtensions\Query\Mysql\Now
numeric_functions:
rand: DoctrineExtensions\Query\Mysql\Rand
default:
connection: default
filters:
softdeleteable:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
enabled: true
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
auto_mapping: true
mappings:
gedmo_loggable:
type: annotation
prefix: Gedmo\Loggable\Entity
dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Loggable/Entity"
alias: GedmoLoggable
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/vendor/org/comp-bundle/Entity'
prefix: 'Org\CompBundle\Entity'
alias: Drm
dql:
datetime_functions:
timetosec: DoctrineExtensions\Query\Mysql\TimeToSec
timediff: DoctrineExtensions\Query\Mysql\TimeDiff
now: DoctrineExtensions\Query\Mysql\Now
numeric_functions:
rand: DoctrineExtensions\Query\Mysql\Rand
Last but not least I do have the following setup at org\compbundle\Resources\services.yaml:
services:
_defaults:
autowire: true
autoconfigure: true
public: false
bind:
$logger: '#Psr\Log\LoggerInterface'
Org\CompBundle\Repository\:
resource: '../../Repository/{Case,Main}'
exclude: ['../../Repository/**/*Interface.php']
tags: ['doctrine.repository_service']
Org\CompBundle\Interfaces\Queues\QueueRepositoryInterface:
class: Org\CompBundle\Repository\DrmCase\QueueRepository
Org\CompBundle\Interfaces\Cases\CasesRepositoryInterface:
class: Org\CompBundle\Repository\DrmCase\CasesRepository
Doctrine\Common\Persistence\ManagerRegistry: '#doctrine'
What I have done so far?
Read a lot of post here on SO leading to the same solution add cascade={"persist"} to the owning side which I did and I must say did not work.
Read Doctrine docs looking for mistakes on my entities definition but so far everything looks fine to me.
I did found this which is helpful but I keep questioning myself why would Doctrine tries to insert and existent entity just because of the reference? Is there any way to get this working?
I do not want the EntityB persisted nor updated, it already exists. I do want the new EntityA have a FK to an existent record in EntityB.
During the weekend a work colleague did work very hard to find out what was causing the issue and after a lot of hours debugging how Doctrine and the UoW works he found where the problem was: how Doctrine and the Repository pattern works. Let me explain a little bit.
If you check this closer and go deep inside Doctrine you will notice how the following code leads to two different entities manager:
public function __construct(RepositoryB $repositoryB, EntityManagerInterface $entityManager)
{
$this->repositoryB = $repositoryB; // spin his own EM
$this->entityManager = $entityManager; // this is a new EM object
}
So:
$entBRef = $this->repositoryB->find(1);
Is being fetched through another EM and since I am using $this->entityManager to persist/flush the recently created entityA object then Doctrine sees $entBRef as a new entity that has to be persisted.
Our solution was to fetch everything through the same repository class which I do not like so much because we are querying things that does not belongs there and we had to ever persist/flush using the same EM.
If you have any other solution it is more than welcome.
I'm working with multiple Entity Managers, followed Symfony doc from here,
but I want to use two entity manager for one dir.
It's not working properly in findAll or findOneBy query, it's showing the result for 'default' entity manager.
in config/packages/doctrine.yaml :
dbal:
# configure these for your database server
default_connection: default
connections:
default:
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
default_table_options:
charset: utf8mb4
collate: utf8mb4_unicode_ci
url: '%env(DATABASE_URL)%'
blog:
driver: 'pdo_mysql'
server_version: '5.7'
url: '%env(DATABASE_BLOG_URL)%'
charset: utf8mb4
orm:
auto_generate_proxy_classes: true
default_entity_manager: default
entity_managers:
default:
connection: default
naming_strategy: doctrine.orm.naming_strategy.underscore
mappings:
Main:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: Main
blog:
connection: blog
naming_strategy: doctrine.orm.naming_strategy.underscore
mappings:
blog:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: blog
in controller:
$entityManager = $this->getDoctrine()->getManager('blog');
$University = $entityManager->getRepository(University::class)
->findOneBy(array('Code' => $Code));
i would recommend inject the connection as a service in your Controller and leverage autowiring
//CONTROLLER
public function testController(YourService $service){
return $service->test();
}
//services.yml
App\Service\YourService:
public: true
arguments: ['#doctrine.orm.entity_manager','#doctrine.orm.blog']
//src/service/YourService.php
class YourService {
private $blog,$em;
public function __construct(EntityManager $em, EntityManager $blog) {
$this->em = $em
$this->blog = $blog;
}
public function test()
{
//connect to blog
$this->blog->getRepository(your_entity::class)->findAll();
//connect to default
$this->em->getRepository(your_entity::class)->findAll();
}
Are you trying to put the name of your second DB in the second argument of the function getRepository, like this:
$University = $entityManager->getRepository(University::class, 'blog')
->findOneBy(array('Code' => $Code));
Update 2:
Use only this configuration, without specify dir, but by using this, you will obligate to use the vanilla SQL to intercate with your DB:
blog:
connection: blog
naming_strategy: doctrine.orm.naming_strategy.underscore
my last suggestion will be to create differente folders Entities for each connection, and duplicate in it the sames entities, and like this you can use the ORM DOCTRINE properly.
I've create CompilerPass class to set some data from database as parameters:
class ParametersCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$em = $container->get('doctrine.orm.default_entity_manager');
$params = $em->getRepository(Setting::class)->findAll();
}
}
but I get this error:
An exception occurred in driver: SQLSTATE[HY000] [1102] Incorrect database name 'nv_097f203e25c61d94_resolve_database_url_c9a61b2f5dc3b858f85dcd10be22549a'
When I get the entity manager e.g. in controller via doctrine.orm.default_entity_manager service everything works fine.
doctrine.yaml:
parameters:
env(DATABASE_URL): ''
doctrine:
dbal:
driver: 'pdo_mysql'
server_version: '5.4'
charset: utf8mb4
default_table_options:
charset: utf8mb4
collate: utf8mb4_unicode_ci
url: '%env(resolve:DATABASE_URL)%'
orm:
auto_generate_proxy_classes: true
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
mappings:
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
You can't access a service at build time in a CompilerPass, the container is not generated yet. A CompilerPass is meant to write things in the generated .php file that will be loaded later.
You probably just want a standard service which loads your configuration in its constructor and provide them through getters.
In a Symfony 4 application I have configured multiple entity managers.
I want my functional tests to automatically create DB tables for both managers.
However, when I run my test; PHP unit encounters an error that says
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
Table 'test.example' doesn't exist
config/packages/doctrine.yaml:
doctrine:
dbal:
connections:
default:
url: '%env(resolve:DATABASE_URL)%'
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
custom:
url: '%env(resolve:DATABASE_URL)%'
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
orm:
default_entity_manager: default
auto_generate_proxy_classes: '%kernel.debug%'
entity_managers:
default:
connection: default
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
mappings:
Model:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity/Model'
prefix: 'App\Entity\Model'
alias: Model
custom:
connection: custom
naming_strategy: doctrine.orm.naming_strategy.underscore
mappings:
Custom:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity/Custom'
prefix: 'App\Entity\Custom'
alias: Custom
To create tables and load Fixtures I'm currently using the Liip Functional Test Bundle.
A simple test looks like this:
tests\Functional\GeneralControllerTest.php:
class GeneralControllerTest extends WebTestCase
{
/**
* {#inheritdoc}
*/
protected function setUp()
{
$this->loadFixtures([
SomeFixtures::class,
MoreFixtures::class,
]);
}
/**
* #dataProvider providePageUris
* #test
* #param string $uri
*/
public function checkThatPageLoads($uri)
{
$client = static::createClient();
/* ... more code ... */
$client->request(Request::METHOD_GET, $uri);
static::assertEquals(Response::HTTP_OK, $client->getResponse()->getStatusCode());
}
/**
* #return array
*/
public function providePageUris()
{
return [
["/dashboard"],
];
}
}
How can I make my Test Case create database tables for the other custom Doctrine EntityManagers?
I have tried adding:
$this->loadFixtures([], true, "custom");
and also:
$this->runCommand("doctrine:schema:create --env=test --em=custom");
to the setUp() method of the Test Case, but this did not result in what is needed. The database tables all need to be created before any Fixture is loaded into the database.
To not have tables in a different entity manager and connection removed when loading data fixtures I changed the doctrine configuration with distinct environment variables.
config/packages/doctrine.yaml:
doctrine:
dbal:
connections:
default:
url: '%env(resolve:DATABASE_URL)%'
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
custom:
url: '%env(resolve:DATABASE_URL_CUSTOM)%'
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
According to the code for the WebTestCase on GitHub the second argument should contain the name of the object manager. I am not sure if specifying custom is enough or if you have to specify the full name doctrine.entity_manager.custom though.
I'm building an API with Symfony 3.4 and api-platform. I want to use soft delete on my entity. I've installed DoctrineExtensions and StofDoctrineExtensionsBundle.
config.yml:
doctrine:
dbal:
connections:
default:
[…]
orm:
entity_managers:
default:
naming_strategy: doctrine.orm.naming_strategy.underscore
connection: default
mappings:
[…]
filters:
softdeleteable:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
enabled: true
And my entity :
<?php
namespace AppBundle\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* MyEntity
*
* #ORM\Table(name="MyEntity", schema="MyEntity")
* #ORM\Entity(repositoryClass="AppBundle\Repository\MyEntityRepository")
* #Gedmo\SoftDeleteable(fieldName="deletedAt")
* #ApiResource
*/
class MyEntity
{
/**
* #var \DateTime
* #ORM\Column(name="deleted_at", type="datetime")
*/
private $deletedAt;
[…]
This is not working. I'm aware that I need to configure something (namely the EventManager), but I don't know how.
Here is the error I get when I try to create an entity
Listener "SoftDeleteableListener" was not added to the EventManager!
I think I've done everything that page explains : StofDoctrineExtensionsBundle documentation
Any help would be greatly appreciated.
Try the following configuration at your config.yml
doctrine:
orm:
entity_managers:
default:
naming_strategy: doctrine.orm.naming_strategy.underscore
connection: default
mappings:
[…]
filters:
softdeleteable:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
enabled: true
stof_doctrine_extensions:
default_locale: %locale%
orm:
default:
softdeleteable: true
Note: My configuration looks like:
orm:
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
default:
auto_mapping: true
filters:
softdeleteable:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
enabled: true
Seems that you're customizing your mappings so be sure you're autoloading the SoftDeleteable classes properly.