Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2: Find entity using entity relations [duplicate]

Say I have two entities in Doctrine2 that are related to each other, Models\User and Models\Comment. If I do this in Doctrine 2.0.0...

<?php
// $em instanceof EntityManager, $user instanceof Models\User
$comments = $em->getRepository('Models\Comment')
    ->findBy(array('user' => $user, 'public' => true));

...I get a PHP error:

Severity: Notice

Message: Object of class Models\User to string conversion

Filename: DBAL/Connection.php

Line Number: 574

This shouldn't happen, right? If I use the QueryBuilder and setParameter('user', $user) it works as expected.

like image 593
pdd Avatar asked Jan 06 '11 19:01

pdd


2 Answers

Query by relationship is allowed, but you have to pass the Identifier in there. Query by object is not yet supported and will only make it into 2.1.

<?php
// $em instanceof EntityManager, $user instanceof Models\User
$comments = $em->getRepository('Models\Comment')
->findBy(array('user' => $user->getId(), 'public' => true));
like image 199
beberlei Avatar answered Oct 04 '22 17:10

beberlei


For symfony 4.1 this code worked for me.

$comments = $this->getDoctrine()
                ->getRepository(Models\Comment::class)
                ->findBy(
                ['user' => $user->getId(), 'public' => true]
);
like image 34
vimuth Avatar answered Oct 04 '22 17:10

vimuth