如何在dql中实现连接?

new9mtju  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(311)

我需要在条令中执行一个简单的查询(使用symfony3.3)。
我有包含描述的“articles”表和包含与文章描述对应的id的“packets”表。在标准sql中,这非常简单

SELECT p.article_id, a.description 
FROM Articles a 
JOIN Packets p 
ON p.article_id=a.id

如何在教义中做到这一点?我几乎什么都试过了,但什么都没用!请帮忙

jaql4c8m

jaql4c8m1#

来自zend项目的代码,尽管我认为symfony并没有什么不同。
在某个函数(如存储库函数)中使用querybuilder:

// These use statements to indicate which to use in case of duplicate class names
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Query\Expr\Join;

$qb = $this->createQueryBuilder('p'); //"p" for packet
$qb->select('p.description', 'art.id')
    ->join(
    'p.article',         // "p" for Packet Entity. "article" for property on Packet Entity
    'art',               // "art" as short name for relation
    Join::WITH,          // Join type
    'art.id = :article'  // the param on which should the join occur
)
    ->setParameter('article', $article); // Set the param with an instance

$result =  $qb->getQuery()->getResult(); // Get the result

如果这是一个双向关系,您可以简单地使用默认值 EntityRepository 条令规定的职能。
例如:

$packets = $this->getObjectManager()->getRepository(Packet::class)->findBy(['article' => $article->getId()]);

如果在实体中正确设置,则更容易:

$packets = $article->getPackets();
rpppsulh

rpppsulh2#

试着用魔法的方法
在控制器中,类似于:

$em = $this->getDoctrine()->getManager();
$packets =  $em->getRepository('NameOfYourBundle:Packets')->findByArticles($id);

相关问题