【发布时间】:2021-09-24 05:58:59
【问题描述】:
我在一个项目中使用 Symfony 5 和 Doctrine 2.9,我需要在同一个表上建立多对一关系(自引用)。
为此,我使用了以下链接https://www.doctrine-project.org/projects/doctrine-orm/en/2.9/reference/association-mapping.html
对于一对多、自引用关系,它表示:
<?php
/** @Entity */
class Category
{
// ...
/**
* One Category has Many Categories.
* @OneToMany(targetEntity="Category", mappedBy="parent")
*/
private $children;
/**
* Many Categories have One Category.
* @ManyToOne(targetEntity="Category", inversedBy="children")
* @JoinColumn(name="parent_id", referencedColumnName="id")
*/
private $parent;
// ...
public function __construct() {
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
}
感谢我可以使用php bin/console make:entity 更新我的实体并添加所需的关系。
问题是,当我的实体使用新关系更新时,我创建了一个php bin/console make:migration 以生成所需的迁移,但没有检测到任何更改。
这并不重要,因为我可以手动生成迁移,但是当我手动更新表时,通过添加外键和关联索引,在下一次迁移时,学说建议我删除外键,索引和属性(parent_id)。
有解决这个问题的办法吗?
感谢您的宝贵时间,
纪尧姆
【问题讨论】:
-
在使用迁移时,您不应该尝试手动更新架构,因为学说会尝试在下次迁移时覆盖它。尝试更新您的
$parent,仅使用:* @ORM\ManyToOne(targetEntity=Category::class, inversedBy="children") -
感谢您的回答,将这个:
/** * @ORM\OneToMany(targetEntity="Category", mappedBy="parent") */ private $children; /** * @ORM\ManyToOne(targetEntity="Category", inversedBy="children") */ private $parent;放在我的关联实体中,我仍然没有生成迁移。我不知道当我们尝试生成具有自引用关系的迁移时,symfony 迁移制造商是否有困难。谢谢。 -
我想知道,我有类似的自引用关联,我没有问题,你的学说版本和制造商捆绑包是什么?
-
你有一些关于 Doctrine 的缓存吗?你能把你的配置文件添加到你的问题中吗(cache.yaml、教义.yaml、教义_migrations.yaml ...)
-
感谢您的回答,就像@qdequippe 说的那样,我清除了 Doctrine 的缓存并且它起作用了。以前我只做过
php bin/console cache:clear。谢谢你的时间。我可以在下面添加答案还是您要添加它(如果您愿意,我会为您投票以寻求帮助?)
标签: symfony doctrine-orm doctrine