教义灯具加载,具有问题设置引用(外键)违反了-not-null约束 [英] Doctrine fixtures load, having issue setting references (foreign key) violates -not-null constraint

查看:103
本文介绍了教义灯具加载,具有问题设置引用(外键)违反了-not-null约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Doctrine Fixtures将一些数据加载到数据库中,
有3个不同的表User,Theme和Sous_Theme,最后两个表具有外键,Theme为(user.id)和Sous_Theme作为两个外键(user.id& theme.id)

I'm using Doctrine Fixtures, to load some data into my database, There is 3 different tables User, Theme and Sous_Theme, the last two Tables have foreign Keys, Theme as (user.id) and Sous_Theme as two foreign keys (user.id & theme.id)

我的 AppFixtures.php 类的设置方式如下每个模型值已经以这种方式写入:

My AppFixtures.php class is set up in a way with having each model value already written in such way :

 private const USERS = [
      [
          'last_name' => 'Goodman',
          'first_name'=> 'Robert',
          'email' => 'robert@foobar.com',
          'job' => 'Admin_Tester',
          'password' => 'blablablablablbal',
          'username' => 'blablablabla',
          'roles' => [USER::ROLE_ADMIN]
      ]...
]



private const THEMES =
    [
        ['name' => 'A theme'],
        ['name' => ' A theme 2']
  .....
]

private const SOUSTHEMES = [
    [
        'name' => 'blablabla',
        'part1' => true, //boolean
        ...
    ],

在写我的SOUSTHEMES部分之前

Before writting the SOUSTHEMES part i have loaded the Users and Themes values with the reference it worked perfectlty :

public function loadTheme(ObjectManager $manager)
    {
        foreach (self::THEMES as $themeDate){
            $theme = new Theme();
            $theme->setName($themeDate['name']);
            $date = new \DateTime();
            $date->modify('-'. rand(0, 10) . 'day');
            $theme->setCreatedAt($date);
            //// Setting user Id into our Theme table.
            $theme->setUser($this->getReference(
                self::USERS[rand(0, count(self::USERS) - 1)]['last_name']));
            $manager->persist($theme);
        }
        $manager->flush();
    }

我现在正在尝试加载带有主题theme.id和user.id的sothethemes:

now im trying to load the sousthemes with the references theme.id and user.id :

public function loadSousThemes(ObjectManager $manager){
        foreach (self::SOUSTHEMES as $sousthemeData){
            $sousthemes = new SousTheme();
            $sousthemes->setName($sousthemeData['name']);
            $date = new \DateTime();
            $date->modify('-'. rand(0, 10) . 'day');
            $sousthemes->setCreatedAt($date);
   

            //// Setting boolean values
            $sousthemes->setPart1($sousthemeData['part_n1']);
  $sousthemes->setUsername($this->setReference(
                self::USERS[rand(0, count(self::USERS) - 1)]['last_name'], $sousthemes));
            $sousthemes->setTheme($this->setReference(
                self::THEMES[rand(0, count(self::THEMES) - 1)]['name'], $sousthemes));

            $manager->persist($sousthemes);
        }
        $manager->flush();

我已经开始使用 getReference()方法,但是我得到了ref不存在,所以我切换到 addReference()我遇到了另一个错误,说该ref已经存在,我需要使用 setReference()覆盖它,所以我将方法更改为 setReference()现在我得到一个错误

I have started with the getReference() method but i got the ref doesnt exist so i switched to the addReference() i got another error saying the ref already exist that i need to use the setReference() to override it so i changed my method to setReference() now i get an error

SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column "theme_id" violates not-null constraint 

我在 user.id 也是。
getReference 在我将user.id值添加到主题中时可以完美地工作,但是它无法在Southeme上工作,我试图弄清楚为什么,是这是因为我要注入两个我非常怀疑的外键,我不知道自己缺少什么,而且在有人说出来之前,是的,我是先按正确的顺序加载用户的值,然后再加载主题,然后再加载主题:

i get the same error on user.id too. The getReference worked perfectly on when i added the user.id value to my theme but it isnt working on for southeme i'm trying to figure out why, is it because i'm injecting two foreign keys which is something i highly doubt, i dont know what i'm missing and before anybody says it lol Yeah i'm loading up my values in the right order user first then theme followed by sousthemes :

public function load(ObjectManager $manager)
    {
        $this->loadUsers($manager);
       $this->loadTheme($manager);
       $this->loadSousThemes($manager);
    }

这是UploadUsers函数:

here is the UploadUsers function :

public function loadUsers(ObjectManager $manager)
    {
        foreach (self::USERS as $userData)
        {
            $user = new User();
            $user->setFirstName($userData['first_name']);
            $user->setLastName($userData['last_name']);
            $user->setEmail($userData['email']);
            $user->setJob($userData['job']);
            $user->setPassword($this->passwordEncoder->
            encodePassword($user, $userData['password']));
            $user->setUsername($userData['username']);
            $user->setCreatedAt(new \DateTime());
            $user->setRoles($userData['roles']);
            $this->addReference($userData['last_name'], $user);
            $manager->persist($user);
        }
        $manager->flush();
    }


推荐答案

首先您不需要根本没有addReference / getReference,因为您使用了一个Fixture文件。因此,在您的情况下,您可以保存对象并在设置器中使用它们,例如:

First of all you dont need addReference/getReference at all, because you use one fixture file. So in your case you can just save the objects and use them in setters, for example:

in loadUsers:

public function loadUsers(ObjectManager $manager)
    {
        foreach (self::USERS as $userData)
        {
            $user = new User();
            ///...
            $manager->persist($user);

            $this->users[$userData['username']] = $user;
        }
        $manager->flush();
    }

and in loadTheme:

$theme->setUser($this->users[self::USERS[rand(0, count(self::USERS) - 1)]['username']]);

您不需要引用,因为您可以访问对象,当灯具位于单独的文件中时,引用非常有用,因为这样您就可以无权访问在不同灯具文件中创建的对象。
此处描述: https ://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html#sharing-objects-between-fixtures

You dont need references, because you have access to objects, references are useful when fixtures are in separate files, because then you dont have access to the objects created in different fixture files. It is described here: https://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html#sharing-objects-between-fixtures .

但是可以说您想使用引用并且我将尝试提供一些指针来修复您已经拥有的代码。您说通过引用加载用户可以处理主题:

But lets say you want to use references and I will try to give pointers that will fix the code you already have. You say loading users by reference worked on themes:

$theme->setUser($this->getReference(self::USERS[rand(0, count(self::USERS) - 1)]['last_name']));

之所以有效,是因为您在 loadUsers 中添加了引用:

It works because you added the reference in loadUsers:

$this->addReference($userData['last_name'], $user);

因此在 loadUsers 之后,您可以使用以下引用:

So after loadUsers you have those references available:

User objects:
 - Goodman
 - ...

现在,每当调用 $ this-> getReference('Goodman'); 时,您都会获得可以在设置器中使用的User对象。 ,例如setUser();

Now whenever you call $this->getReference('Goodman'); you will get the User object that you can use in setters, ex. setUser();

但是您从未在 loadTheme 中调用 addReference 进行保存

But you never called addReference in loadTheme to save references to your theme objects.

loadTheme 添加 addReference

public function loadTheme(ObjectManager $manager)
    {
        foreach (self::THEMES as $themeDate){
            $theme = new Theme();
            $theme->setName($themeDate['name']);
            // ...
            $theme->setUser($this->getReference(
                self::USERS[rand(0, count(self::USERS) - 1)]['last_name']));
            $manager->persist($theme);

            $this->addReference($theme->getName(), $theme);
        }
        $manager->flush();
    }

因此在 loadUsers 和<$ c之后$ c> loadThemes 这些引用将可用:

So after loadUsers and loadThemes those references will be available:

User objects:
 - Goodman
 - ...

Theme objects:
 - A theme
 - A theme 2
 - ...

最后在您的 loadSousThemes 中:

$sousthemes->setUsername($this->getReference(
                self::USERS[rand(0, count(self::USERS) - 1)]['last_name']));
            $sousthemes->setTheme($this->getReference(
                self::THEMES[rand(0, count(self::THEMES) - 1)]['name']));

请注意,我假设 $ sousthemes-> setUsername()实际上是用于设置用户对象,而不仅仅是用户名(为什么它不称为setUser?)

Note that I assume that $sousthemes->setUsername() is really for setting User object, not just username (why it is not called setUser?)

这篇关于教义灯具加载,具有问题设置引用(外键)违反了-not-null约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆