7

当我跑

console doctrine:fixtures:load --fixtures=src/App/PeopleBundle/DataFixtures/ORM

我不希望教义清除每个具有实体的表。相反,我只想清除明确指定目录中的固定装置的表。

然而,不管目标目录是什么,symfony 似乎都在查找每个包中的每个实体,并清除与每个实体关联的每个表。

我如何指示 symfony2 忽略除我编写了固定装置的特定表之外的所有表?

4

3 回答 3

4

以正确的方式去做这件事并不难。首先,是的,您使用--append,但是您将添加大量您不想要的额外内容。所以你需要在你的fixtures中执行一些基本的检查,看看你是否真的需要添加它们(如果它们已经在数据库中,你不需要)。

我将向您展示的示例是一个简单的示例:我有一个locators包含列的表:idname.

namespace Application\Model\Fixtures;

use Doctrine\Common\DataFixtures\OrderedFixtureInterface,
    Doctrine\Common\DataFixtures\FixtureInterface,
    Doctrine\Common\Persistence\ObjectManager,
    Application\Model\Entity\Locator;

/**
 * Class LoadLocators
 *
 * Pre-populates the locators table
 *
 * @package Application\Model\Fixtures
 */
class LoadLocators implements FixtureInterface, OrderedFixtureInterface
{
    /**
     * @var array The locators names that will be inserted in the database table
     */
    protected $locators = ['id', 'xpath', 'css'];

    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        foreach ($this->locators as $locatorName)
        {
            $locator = $this->findOrCreateLocator($locatorName, $manager);

            /** Check if the object is managed (so already exists in the database) **/
            if (!$manager->contains($locator))
            {
                $manager->persist($locator);
            }
        }

        $manager->flush();
    }

    /**
     * Helper method to return an already existing Locator from the database, else create and return a new one
     *
     * @param string        $name
     * @param ObjectManager $manager
     *
     * @return Locator
     */
    protected function findOrCreateLocator($name, ObjectManager $manager)
    {
        return $manager->getRepository('Application\Model\Entity\Locator')->findOneBy(['name' => $name]) ?: new Locator($name);
    }

    /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 1;
    }
}

此处的简单更改是,如果该对象已存在于数据库中,则找到它并改用该对象。真的就是这么简单。

我现在运行的命令--append在最后,但如果数据已经存在,它不会追加。

于 2015-03-17T12:39:26.530 回答
3

您认为 Doctrine 应该如何确定要清除的内容和不清除的内容?夹具中没有信息告诉它将加载哪些实体。如果你真的需要这个,你必须手动完成。

首先,您可以使用该--append选项来避免清除数据库。其次,您可以在您的固定装置中做的第一件事是截断相关的表格。

于 2012-08-10T07:02:17.520 回答
1

您可以使用该--fixtures选项加载选定的灯具。

--append您一起可能能够控制您想要执行的操作,从而清除 Elnur 所说的对实体管理器管理的每个表的影响。

于 2014-09-29T13:02:45.863 回答