dongluanan7163 2011-05-15 21:29
浏览 34
已采纳

你如何在Doctrine 2中使用实体关系?

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:

$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.

  • 写回答

2条回答 默认 最新

  • dongmeng1402 2011-05-15 23:03
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划