开发者

How do you work with Entity relationship within Doctrine 2?

开发者 https://www.devze.com 2023-03-06 14:35 出处:网络
When you want to insert an Entity you do this: $user = new User(); $user->setEmail(\'john@doe.com\');

When you want to insert an Entity you do this:

$user = new User();
$user->setEmail('john@doe.com');

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

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

Currently, I need to do:

$us开发者_Go百科er = $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.


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();


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号