Search code examples
mysqldatabasedoctrineentitymanager

Using doctrine with multiple MySQL Databases


I'm starting a new project from an existing MySQL DB and I would like to use symfony+doctrine for that. The problem is that my current DB has multiple DB in it. For instance, it has db.tables like:

  • customers.info
  • customers.orders
  • items.catalog
  • items.stock
  • etc....

I've tried to search online but I've realized that one of the problem is that "database" word is used to define 2 very different things: database "software", like mysql, postgres, mariaDB, etc... and databases as in SQL "CREATE DATABASE".

So when I'm looking at symfony doc, I found this page, which states that I cannot use Doctrine ORM since I have multiple DB: https://symfony.com/doc/current/doctrine/multiple_entity_managers.html

But the more I read it, the more I have the feelings that what there are saying is "you need one entityManager for Mysql, one for Postgres, etc... and Entities cannot define associations across different entity managers" and not "Entities cannot define associations across different DB from the same DB software"

AM I right? and if yes, how can I achieve such a thing, knowing that I need to provide a database name in the connection URL (like mysql://user:pass@127.0.0.1/oneOfMyDb )

Thanks!


Solution

  • Ok so I finally found the answer, which may be useful for other people in the same situation.

    It is possible to use doctrine with multiple database/schema in mySQL. yes, the problem here is that MySQL kinda mixed the concept of DB and schema, hence the confusion.

    In order to do this, you need to declare the table and schema used for every entity, for instance:

    <?php
    
    namespace App\Entity;
    
    use App\Repository\PropertyRepository;
    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * @ORM\Entity(repositoryClass=PropertyRepository::class)
     * @ORM\Table(name="property", schema="myOtherDB")
     */
    class Property
    {
     // some stuff here...
    }
    

    This way, no matter which DB name you declare in the connection, it will connect to you other DB (schema) and you will be able to fetch datas from foreign keys, even if this data is stored in a table in a different DB (schema).

    I hope this will help some people!