如何在Doctrine中的多对多JoinTable上添加索引定义?

5 浏览
0 Comments

如何在Doctrine中的多对多JoinTable上添加索引定义?

我有两个实体和一个用于多对多关系的连接表:

Entities/Product.php

namespace App\Entities;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
 * @ORM\Table(name="product")
 * @ORM\Entity(repositoryClass="App\Repositories\ProductRepository")
 */
class Product
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     *
     * @var int
     */
    private $id;
    /**
     * 多个产品有多个流程
     *
     * @ORM\ManyToMany(targetEntity="Process", inversedBy="products")
     * @ORM\JoinTable(name="product_process")
     *
     * @var \Doctrine\Common\Collections\ArrayCollection
     */
    private $processes;
    public function __construct()
    {
        $this->processes = new ArrayCollection();
    }
}

Entities/Process.php

namespace App\Entities;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
 * @ORM\Table(name="process")
 * @ORM\Entity(repositoryClass="App\Repositories\ProcessRepository")
 */
class Process
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     *
     * @var int
     */
    private $id;
    /**
     * 多个流程有多个产品
     *
     * @ORM\ManyToMany(targetEntity="Product", mappedBy="processes")
     *
     * @var \Doctrine\Common\Collections\ArrayCollection
     */
    private $products;
    public function __construct()
    {
        $this->products = new ArrayCollection();
    }
}

在运行doctrine:migrations:diff命令时,它创建了productprocessproduct_process表。

我想在product_process连接表上创建索引和外键。

通过Doctrine ORM注释,是否可以在其他两个实体(ProductProcess)中实现这一点?

0
0 Comments

如何在Doctrine中在Many-To-Many JoinTable上添加索引定义?

在Doctrine中创建Many-To-Many关联时,生成的数据库表已经包含了必要的主键索引和外键关系。如果需要其他的索引定义,可以创建一个独立的实体"ProductProcess",并在该实体上声明两个OneToMany关联(如果需要,可以在相关实体上声明ManyToOne关系)。额外的映射信息可以直接在该实体上声明。

问题的原因是在生成的SQL迁移中,作者手动添加了一些索引定义。然而,当运行"migrations:diff"命令时,Doctrine会自动生成索引名称,导致SQL迁移与手动添加的索引定义不一致。

解决方法是不需要为主键添加索引,因为主键总是自动创建索引的。此外,Doctrine会自动管理索引的命名,如果手动设置了索引,Doctrine将重新命名这些索引。

作者注意到当从实体生成迁移时,它会创建所有的外键和索引,如果手动设置了索引名称,那么它会再次生成这些索引,在运行"migrations:diff"命令时会出现问题。

问题的原因是作者手动添加了索引定义,但Doctrine会自动生成索引名称并管理索引的命名。解决方法是不需要手动为主键添加索引,而是让Doctrine自动管理索引的命名。

0