سؤال

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?

هل كانت مفيدة؟

المحلول

Using doctrine, when you define a related entity it's type is the entity class (in this case FrontUser). Therefore firstly your related entity variable name is misleading. It should be e.g.

private $ownerUser;

Then, in order to do a findBy on a related entity field you must supply an entity instance e.g.

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

If you don't have or want to retrieve the user entity you could use a DQL query with the 'uid' as a parameter instead.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top