3

I have two entities Entity1 and Entity2 with a OneToMany relation, but they live in two MySQL databases.

How can I implement those entities with their relation in Symfony?

Is it possible to create two separated bundles where to implement those entities?

1 Answer 1

6

In Doctrine, joining data across databases is not technically “supported” by a designed feature, but you can make it work by tricking Doctrine a little bit.

If you want to build a relationship between entities then they must use the same connection: same database.

The key to getting multiple databases to work is within your entity classes, you need to specify the table name of the entity with a prefix of the name of the database to which the table belongs. Here is an example using annotations:

<?php
namespace Demo\UserBundle\Entity;

use DoctrineORMMapping as ORM;

/**
 * Demo\UserBundle\Entity\User
 *
 * @ORMTable(name="users.User")
 */
class User implements
{
  /* ... */
}

and

<?php
namespace Demo\PostBundle\Entity;

use DoctrineORMMapping as ORM;

/**
 * Demo\PostBundle\Entity\Post
 *
 * @ORMTable(name="posts.Post")
 */
class Post implements
{
  /* ... */
}

and the relation table:

<?php
namespace Demo\PostBundle\Entity;

use DoctrineORMMapping as ORM;

/**
 * Demo\PostBundle\Entity\Post
 *
 * @ORMTable(name="posts.Post")
 */
class Post implements
{
    /**
     * @ORM\ManyToOne(targetEntity="\Demo\UserBundle\Entity\User")
     **/
    private $user;

    /* ... */

    /**
     * Set user
     *
     * @param \Demo\UserBundle\Entity\Site $site
     * @return Post
     */
    public function setUser($user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \Demo\UserBundle\Entity\Site
     */
    public function getUser()
    {
        return $this->user;
    }
}

Here an article about it.

Hope this help

Sign up to request clarification or add additional context in comments.

9 Comments

Grazie! And can I set that database name string as a config parameter? Ciao!
hi @ShinDarth with the doctrine annotation i think is not possible insert parameters but you can try with the xml annotation and put a params with %db_name_1% hope this help
hi @ShinDarth have you tried my solutions? Is it working?
hello @matteo, unfortunately so far I didn't have the time and I guess I won't have for I while. But I'll let you know, thanks for asking!
@Vinayak seems not possibile, for this trick must use the same connection: same database.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.