首页 > 解决方案 > Symfony 4(Doctrine 2.7)联合继承

问题描述

我想在我的 Symfony 项目中按域划分用户。

到目前为止我的课程:

<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class Domain
{
    /**
     * @ORM\Id
     * @ORM\Column(type="smallint")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", unique=true, length=255, nullable=false)
     */
    private $name;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="domain")
     */
    private $users;
}

<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Entity
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="domain_id", type="smallint")
 * @ORM\DiscriminatorMap({"0":"App\Entity\User","1":"App\Entity\User1","2":"App\Entity\User2","3":"App\Entity\User3"})
 */
class User
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer", options={"unsigned":true})
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Domain", inversedBy="users")
     * @ORM\JoinColumn(name="domain_id", referencedColumnName="id")
     */
    private $domain;
}
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Entity
 */
class User1 extends \App\Entity\User
{
    /**
     * @ORM\Column(type="string", unique=true, length=255, nullable=false)
     */
    private $email;
}
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Entity
 */
class User2 extends \App\Entity\User
{
    /**
     * @ORM\Column(type="string", unique=true, length=255, nullable=false)
     */
    private $email;
}
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Entity
 */
class User3 extends \App\Entity\User
{
    /**
     * @ORM\Column(type="string", unique=true, length=255, nullable=false)
     */
    private $email;
}

当我运行时:

C:\Users\user\PhpstormProjects\test>php bin\console doctrine:schema:create --dump-sql
In SchemaException.php line 119:
  The column 'domain_id' on table 'user' already exists.
doctrine:schema:create [--dump-sql] [--em [EM]] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command>
C:\Users\user\PhpstormProjects\test>

正如我们所看到的, domain_id 与鉴别器字段冲突,我没有必要用相同的值复制它。总体思路是通过使用不同的表来分隔用户和域。对于单表继承,这很容易,但出于性能原因,我必须拆分它们。我想,也许还有其他解决方案?

标签: databaseinheritancedoctrinesymfony4discriminator

解决方案


推荐阅读