Php 尝试使用原则2连接两个简单表
我是Symfony 2和Doctrine 2的初学者。我有两种模式:博客和评论。它们通过Php 尝试使用原则2连接两个简单表,php,mysql,symfony,join,doctrine-orm,Php,Mysql,Symfony,Join,Doctrine Orm,我是Symfony 2和Doctrine 2的初学者。我有两种模式:博客和评论。它们通过blog\u idFK在comment表中相互关联 我只想创建一个简单的方法,获取博客id,检索该博客和相关评论。而不是在惰性加载相关注释中执行另一个查询 以下是我尝试过的: <?php namespace Blogger\BlogBundle\Entity\Repository; use Doctrine\ORM\EntityRepository; class BlogRepository ex
blog\u id
FK在comment
表中相互关联
我只想创建一个简单的方法,获取博客id,检索该博客和相关评论。而不是在惰性加载相关注释中执行另一个查询
以下是我尝试过的:
<?php
namespace Blogger\BlogBundle\Entity\Repository;
use Doctrine\ORM\EntityRepository;
class BlogRepository extends EntityRepository
{
public function getBlogWithComments($id)
{
$query = $this->getEntityManager()->createQuery('
SELECT b, c
FROM BloggerBlogBundle:Blog b
WHERE b.id = :id
JOIN b.id c
WHERE b.id = c.blog');
$query->setParameter("id", $id);
return $query->getResult();
}
}
AJOIN
与DQL是通过引用实体之间的关系来完成的,它只需要走一条路。我的意思是b.comment c
是所有需要的,没有必要引用c.blog
public function getBlogWithComments($id)
{
return $this->getEntityManager()
->createQuery('
SELECT b, c
FROM BloggerBlogBundle:Blog b
JOIN b.comment c
WHERE b.id = :id
')
->setParameter("id", $id)
->getResult();
}
好的,那就行了。但是,当我再次运行它时,在BloggerBlogBundle:Blog:show.html.twig的第3行中,对于键为“0”的数组,我在视图键“title”中得到了一个错误。这说明Blog
(或您所称的)是一个数组。因此,您需要使用twig的for
语句来循环遍历每个blog
帖子的blog
数组。哦,这也行得通。但我想知道为什么它会返回数组?我只检索了一个有评论的博客。正如我所检查的,数组只有一个元素blog[0]
,它包含整个blog对象和相关注释。查询通常可能返回多个对象,因此它将始终返回一个数组。因为您知道它总是一篇文章,所以您可以通过执行类似$query=$this->getEntityManager()的操作来更改存储库中的函数以返回对象。。。;返回$query[0];好的,我用getSingleResult()
更改了getSingleResult()
。