您如何处理原则 2 中的实体关系?

发布于 2024-11-07 05:44:57 字数 681 浏览 5 评论 0原文

当您想要插入一个实体时,您可以这样做:

$user = new User();
$user->setEmail('[email protected]');

$em->persist($user);
$em->flush();

但是如果我想创建一篇可以有一个用户的文章怎么办?

目前,我需要做:

$user = $em->getRepository('User')->find($id);
$article->setUser($user);

这是因为关系,Doctrine 2 要求一个 User 实体。

但是,我无法“模拟” User 对象,因为我不希望手动设置 id,因此我不能这样做

$user = new User();
$user->setId(45);

我对这种行为错了吗?你怎么做?

即使使用缓存,加载用户实体只是为了设置关系也可能会影响性能,这并不总是一个选项,尤其是对于更新而言。

When you want to insert an Entity you do this:

$user = new User();
$user->setEmail('[email protected]');

$em->persist($user);
$em->flush();

But what if I want to create an article which can have one User;

Currently, I need to do:

$user = $em->getRepository('User')->find($id);
$article->setUser($user);

This is because of the relationship, Doctrine 2 asks for an User entity.

However, I can't "mock" an User object, because I don't want the id be set manually, therefore I can't do:

$user = new User();
$user->setId(45);

Am I wrong about this behavior, how do you do?

It can be performance matter to load the User entity just to set the relationship, even with a cache, which cannot be always an option, especially for an update.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

幽梦紫曦~ 2024-11-14 05:44:57

如果您没有方便的托管用户实体,那么您想要的是 参考代理,EM 很乐意为您提供:

<?php
$article = new Entity\Article();
$article->setTitle('Reference Proxies Rule');
$article->setBody('...');
$article->setUser($em->getReference('Entity\User',45));
$em->persist($article);
$em->flush();

If you don't have a managed User entity handy, what you want is a reference proxy, which the EM will be happy to give you:

<?php
$article = new Entity\Article();
$article->setTitle('Reference Proxies Rule');
$article->setBody('...');
$article->setUser($em->getReference('Entity\User',45));
$em->persist($article);
$em->flush();
宛菡 2024-11-14 05:44:57

为什么您的文章首先要求用户拥有 ID?您应该能够在没有 EntityManager 的情况下对实体进行单元测试,如果不能,那么您可能做错了什么。然后,当您进行功能单元测试时,它是

我建议您观看单元测试 Doctrine 2 实体 Zend 演员表。

Why does your Article require a User to have an Id in the first place? You should be able to unit testing your Entities without the EntityManager, if you can't then you're probably doing something wrong. Then when you do functional unit tests it's as simple as this.

I recommend you watch Unit Testing Doctrine 2 Entities from Zend Casts.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文