Symfony and Doctrine: cross database relations

被刻印的时光 ゝ 提交于 2020-01-01 07:21:09

问题


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:


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



来源:https://stackoverflow.com/questions/36696793/symfony-and-doctrine-cross-database-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!