Symfony和教义:跨数据库关系 [英] Symfony and Doctrine: cross database relations

查看:132
本文介绍了Symfony和教义:跨数据库关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有OneToMany关系的实体 Entity1 Entity2 ,但是它们存在于两个MySQL数据库中.

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

如何在Symfony中实现具有其关系的实体?

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

是否可以在其中实现这些实体的地方创建两个单独的捆绑包?

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

推荐答案

在Doctrine中,设计功能在技术上不支持"跨数据库的联接数据,但是您可以通过欺骗Doctrine使其工作.

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
{
  /* ... */
}

<?php
namespace Demo\PostBundle\Entity;

use DoctrineORMMapping as ORM;

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

和关系表:

<?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.

希望获得帮助

这篇关于Symfony和教义:跨数据库关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆