0

To simplify, two entities are defined: User and Comment. User can post many comments and every comment has only one user assigned, thus Comment entity has:

/**
 * @var \Frontuser
 *
 * @ORM\ManyToOne(targetEntity="Frontuser")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="ownerUserID", referencedColumnName="id")
 * })
 */
private $owneruserid;

However, when in action:

$orm = $this->getDoctrine()->getManager();
$repo = $orm->getRepository('CompDBBundle:Comment');
$repo->findBy(array('owneruserid' => $uid);

Error occured, that there's no such field like owneruserid.

How can I fetch all the user's comments then? The same happens to similar relations in my DB - looks likes you cannot run find() with foreign keys as parameters. I believe a function $user->getComments() should be automatically generated/recognised by Doctrine to allow efficient, quick access to related entities.

The example's simple but, what if there are more entities related to my User in the same way? Do I have to declare repositories for each and try to fetch them by it's owneruserid foreign keys?

4

1 回答 1

2

使用原则,当您定义相关实体时,它的类型是实体类(在本例中为 FrontUser)。因此,首先您的相关实体变量名称具有误导性。它应该是例如

private $ownerUser;

然后,为了在相关实体字段上执行 findBy,您必须提供一个实体实例,例如

$orm = $this->getDoctrine()->getManager();
$userRepo = $orm->getRepository('CompDBBundle:FrontUser');
$user = $userRepo->findById($uid);
$commentRepo = $orm->getRepository('CompDBBundle:Comment');
$userComments = $commentRepo->findByOwnerUser($user);

如果您没有或想要检索用户实体,您可以使用带有“uid”作为参数的 DQL 查询。

于 2013-04-24T10:24:40.167 回答