尝试重新加载灯具时出现问题

zii*_*web 0 symfony

当我尝试使用时重新加载我的灯具

php app/console doctrine:fixtures:load

我收到这个错误:

SQLSTATE [23000]:完整性约束违规:1451无法删除或更新父行:外键约束失败(foo_db.Book,CONSTRAINT FK_C29271DD816C6140FOREIGN KEY(author_id)REFERENCES Author(id))

显示状态时显示错误"> purging database".

这是我的代码:

class Book{
...

/**
 * @ORM\ManyToOne(targetEntity="Author", inversedBy="books")
 */
private $author;

... 
}

class Author{
    ...
    /**
     * @ORM\OneToMany(targetEntity="Book", mappedBy="author")
     */
    private $books;

}
Run Code Online (Sandbox Code Playgroud)

更多:我的老板有相同的代码,没有错误.

任何的想法?

sf 2.0.1(刚刚更新)/ ubuntu 10.10.

Mat*_*att 9

如果我猜对了,你使用的是MySQL数据库.如果是,那么您将面临doctrine-fixturesDoctrine2库的当前版本的错误/问题.问题是他们正在使用该TRUNCATE命令清除当前数据库值,但此命令在删除MySQL中的外部关联时出现问题.

这个问题这个磁带库以获取更多信息和解决方法GitHub的仓库.

在我的特定情况下,我从脚本运行此命令,所以为了使命令正常工作,我做:

php app/console doctrine:database:drop --force
php app/console doctrine:database:create

php app/console doctrine:schema:update --force

php app/console doctrine:fixtures:load --append
Run Code Online (Sandbox Code Playgroud)

这样,清除由drop命令完成,并且附加具有与不附加相同的效果,因为在加载灯具时数据库是空的.

我必须承认我不知道为什么你的老板没有问题,也许在他的数据库中没有与作者相关的书.

希望这有帮助.

问候,
马特


Krz*_*owa 5

我已经为 Symfony 4 创建了一个简单的 Event Subscriber 类。修复自引用外键问题所需的全部内容是将以下类添加到 Symfony 4 项目的某处。

这个订阅者在每个 Symfony CLI 命令之前触发。如果命令的名称是doctrine:fixtures:load,它将执行数据库清除,但SET FOREIGN_KEY_CHECKS = 0首先执行。

这解决了问题,无需任何其他修改。

use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ConsoleCommandEventSubscriber implements EventSubscriberInterface
{
    /**
    * @var EntityManagerInterface
    */
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public static function getSubscribedEvents()
    {
        return [
            ConsoleEvents::COMMAND => 'onCommand',
        ];
    }

    public function onCommand(ConsoleCommandEvent $event)
    {
        if ($event->getCommand()->getName() === 'doctrine:fixtures:load') {
            $this->runCustomTruncate();
        }
    }

    private function runCustomTruncate()
    {
        $connection = $this->entityManager->getConnection();

        $connection->exec('SET FOREIGN_KEY_CHECKS = 0');

        $purger = new ORMPurger($this->entityManager);
        $purger->setPurgeMode(ORMPurger::PURGE_MODE_DELETE);
        $purger->purge();

        $connection->exec('SET FOREIGN_KEY_CHECKS = 1');
    }
}
Run Code Online (Sandbox Code Playgroud)