带有固定装置的 symfony 4,getReference 方法不会 return 预期的对象(return PROXY/__CG__/... 而是 User class 的实例)
symfony 4 with fixtures, the getReference method does not return the expected object (return PROXY/__CG__/... instead an instance of User class)
从 symfony 4,我创建了两个固定装置 类。
当我 运行 命令“./bin/console doctrine:fixtures:load”时,我收到此错误:
Argument 1 passed to App\Entity\Article::setAuthor() must be an instance of User, instance of Proxies\__CG__\App\Entity\User given, called in /home/okli/PhpstormProjects/nomads_fiction/src/DataFixtures/ArticleFixtures.php on line 53
从夹具 1(调用的第一个夹具),我使用以下代码创建了一个用户:
$myuser = new User();
$myuser->setName("foo");
...
$em->persist($myuser);
$em->persist();
$this->addReference("foo", $myuser);
$this->log->info("class is : " . get_class($myuser)); // print "class is : App\Entity\User" its good !
从夹具 2 中,我像这样加载了 myuser 对象:
$myuser = $this->getReference("foo");
$this->log->info("class is : " . get_class($myuser)); // print "class is : Proxies\__CG__\App\Entity\User", why not App\Entity\User ?
为什么 getReference 没有 return 我从 fixture 1 return 得到的完全相同的对象?我的错误在哪里?
感谢您的帮助:)
这正是它应该做的。 getReference() 函数允许您获取对标识符已知的实体的引用,而无需从数据库中加载该实体,该实体是为用户生成的 class 的代理对象。完整文档 here
事实上,如果您使用代理对象,学说并不关心。要使代码正常工作,您要做的就是从 Article 实体中的 setAuthor 函数中删除类型提示(即 setAuthor(User $user) 到 setAuthor($user))。
这会起作用,因为您想要通过调用 setAuthor 函数实现的只是建立与实体的关联。由于您已经拥有此实体的标识符,因此不必完全加载它。
编辑: 正如 Matías Navarro Carter 所观察到的,实体代理 classes 扩展了真实实体 classes,因此类型提示无论如何都应该起作用。我猜你忘了在你的 Article 实体中使用适当的命名空间。也许您在 Article.php:
中遗漏了类似的内容
use App\Entity\User;
从 symfony 4,我创建了两个固定装置 类。 当我 运行 命令“./bin/console doctrine:fixtures:load”时,我收到此错误:
Argument 1 passed to App\Entity\Article::setAuthor() must be an instance of User, instance of Proxies\__CG__\App\Entity\User given, called in /home/okli/PhpstormProjects/nomads_fiction/src/DataFixtures/ArticleFixtures.php on line 53
从夹具 1(调用的第一个夹具),我使用以下代码创建了一个用户:
$myuser = new User();
$myuser->setName("foo");
...
$em->persist($myuser);
$em->persist();
$this->addReference("foo", $myuser);
$this->log->info("class is : " . get_class($myuser)); // print "class is : App\Entity\User" its good !
从夹具 2 中,我像这样加载了 myuser 对象:
$myuser = $this->getReference("foo");
$this->log->info("class is : " . get_class($myuser)); // print "class is : Proxies\__CG__\App\Entity\User", why not App\Entity\User ?
为什么 getReference 没有 return 我从 fixture 1 return 得到的完全相同的对象?我的错误在哪里?
感谢您的帮助:)
这正是它应该做的。 getReference() 函数允许您获取对标识符已知的实体的引用,而无需从数据库中加载该实体,该实体是为用户生成的 class 的代理对象。完整文档 here
事实上,如果您使用代理对象,学说并不关心。要使代码正常工作,您要做的就是从 Article 实体中的 setAuthor 函数中删除类型提示(即 setAuthor(User $user) 到 setAuthor($user))。
这会起作用,因为您想要通过调用 setAuthor 函数实现的只是建立与实体的关联。由于您已经拥有此实体的标识符,因此不必完全加载它。
编辑: 正如 Matías Navarro Carter 所观察到的,实体代理 classes 扩展了真实实体 classes,因此类型提示无论如何都应该起作用。我猜你忘了在你的 Article 实体中使用适当的命名空间。也许您在 Article.php:
中遗漏了类似的内容use App\Entity\User;