简体   繁体   中英

How to query in Doctrine2 WHERE = 'value from a related Entity'

The relationship is as easy as Many posts -> one User

// Acme\AppBundle\Entity\UploadPlugin\Post
/**
 * @ORM\ManyToOne(targetEntity="Acme\AppBundle\Entity\AuthBundle\LiveUser")
 * @ORM\JoinColumn(name="posts", referencedColumnName="id")
 **/
private $postOwner;

So when I create a new Post like this :

  $image = new Post();

  $image->setName($imagetitle);
  $image->setPostowner($this->getUser());
  //(...) set further stuff
  $em = $this->getDoctrine()->getManager();
  $em->persist($image);
  $em->flush();

I'd just return a json from the controller:

$posts= $em->createQuery(
    "SELECT p
     FROM GabrielAppBundle:UploadPlugin\Post p"
)->getResult();

$serializer = $this->container->get('jms_serializer');
$json = $serializer->serialize($posts, 'json');

$response =  new Response($json);
$response->headers->set('Content-Type', 'application/json');
return $response;

it returns a JSON like this

[{
"id": 10,
"name": "So das Alkoholfrei",
"path": "so-das-alkoholfrei_546.png", 
"type": "image", 
"post_owner": {
    "uname": "gabriel",
    "fname": "Will",
    "lname": "Smith",
    "ppic": "profilepic_61602.png"
},
"created_at": "2015-06-19T23:58:35+0200",
"updated_at": "2015-06-19T23:58:35+0200"
}
]

Now I need a code that will let me fetch all user posts based on the username, but I don't know how to achieve this.

I need something similar to this ,or another solution

   $posts= $em->createQuery(
        "SELECT p
         FROM GabrielAppBundle:UploadPlugin\Post p WHERE p.postOwner.uname = :username"
    )->setParameter('username','john')
    ->getResult();

You can use a DQL join :

$posts= $em->createQuery(
    "SELECT p, po
     FROM GabrielAppBundle:UploadPlugin\Post p 
     JOIN AcmeAppBundle:AuthBundle\LiveUser po
     WHERE po.uname = :username"
)->setParameter('username','john')
->getResult();

Note, that "SELECT p, po" causes the $postOwner for each post to be hydrated by the query, rather than requiring an additional query to be executed in order to retrieve each one. If you didn't need the $postOwner data but just needed to select based on one of it's values then "SELECT p" would be sufficient.

This query worked for me:

  1. find the first entity by value:

     $postOwner = $em->getRepository('GabrielAppBundle:AuthBundle\\LiveUser')->findOneByUsername('john');
  2. Query the second entity then use first entity object as parameter

    $posts= $em->createQuery( "SELECT p FROM GabrielAppBundle:UploadPlugin\\Post p WHERE p.postOwner = :postOwner" )->setParameter('postOwner',$postOwner);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM