这种关系很简单 很多帖子 - >一个用户
// Acme\AppBundle\Entity\UploadPlugin\Post
/**
* @ORM\ManyToOne(targetEntity="Acme\AppBundle\Entity\AuthBundle\LiveUser")
* @ORM\JoinColumn(name="posts", referencedColumnName="id")
**/
private $postOwner;
所以当我创建一个像这样的新帖子时:
$image = new Post();
$image->setName($imagetitle);
$image->setPostowner($this->getUser());
//(...) set further stuff
$em = $this->getDoctrine()->getManager();
$em->persist($image);
$em->flush();
我只是从控制器返回一个json:
$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;
它返回一个像这样的JSON
[{
"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"
}
]
现在我需要一个代码,让我可以根据用户名获取所有用户帖子,但我不知道如何实现这一点。
我需要类似于此的东西或其他解决方案
$posts= $em->createQuery(
"SELECT p
FROM GabrielAppBundle:UploadPlugin\Post p WHERE p.postOwner.uname = :username"
)->setParameter('username','john')
->getResult();
答案 0 :(得分:2)
您可以使用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();
注意," SELECT p,po"导致每个帖子的$ postOwner被查询补充,而不是要求执行额外的查询以便检索每个帖子。如果您不需要$ postOwner数据,只需要根据其中一个值进行选择,那么" SELECT p"就足够了。
答案 1 :(得分:0)
此查询对我有用:
按值查找第一个实体:
$postOwner = $em->getRepository('GabrielAppBundle:AuthBundle\LiveUser')->findOneByUsername('john');
查询第二个实体,然后使用第一个实体对象作为参数
$posts= $em->createQuery(
"SELECT p
FROM GabrielAppBundle:UploadPlugin\Post p
WHERE p.postOwner = :postOwner"
)->setParameter('postOwner',$postOwner);