Reputation: 61724
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?
Upvotes: 3
Views: 2931
Reputation: 39370
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
Upvotes: 6