【问题标题】:Create new element with doctrine entity manager?使用学说实体管理器创建新元素?
【发布时间】:2016-12-19 14:42:04
【问题描述】:

我在脚本中使用了学说实体管理器,选择和更新始终有效,因此实体管理器已正确初始化:

$article = $entityManager->find('Models\Article', 5);
echo $article->getTitle();
or:
$article->setTitle('Updated!');

但是当我尝试创建/保存新元素然后分页符时,代码是:

$item = new Article();
$item->setAuthorId(1);
$item->setTitle('Created item!');
$entityManager->persist($item);
$entityManager->flush();

像官方documentation page一样创建

我在这里做错了什么?

【问题讨论】:

  • 您遇到了什么错误?
  • “然后分页符”是什么意思?
  • @Youssef 我现在在空白页中尝试,在我执行“flush()”之后出现重定向错误,在 Firefox 中这是消息“页面未正确重定向”
  • 你能检查你的日志吗?
  • 今天什么都没有了...

标签: symfony doctrine-orm doctrine php-7


【解决方案1】:

您似乎无法指定对象与Author 实体的关系:

$item->setAuthorId(1);

可能您的实体Article 与实体Author 有关系。在这种情况下,您应该有一个适当的 setter 方法(简单的 setAuthor(Author $author) )来分配 Author 对象的引用。在这种情况下,您可以使用以下内容:

$item->setAuthor($entityManager->find('Models\Author', 1););

或者更好

$item->setAuthor($entityManager->getReference('Models\Author', 1););

您还可以使用class 关键字引用类对象的简短方式,例如:

$item->setAuthor($entityManager->getReference(Author::class, 1););

希望有帮助

【讨论】:

  • 还有一个 PHP 错误,但也有关系,谢谢大家 :)
猜你喜欢
  • 2013-05-03
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-14
相关资源
最近更新 更多