Doctrine join a table with two

Doctrine join a table with two

早上好,如下图所示,我链接了一些表。

使用 Doctrine (在 Symfony2 中) 我正在尝试获取一个 对象问题数组 它本身包含所有 IssueMessagesIssueStatusChanged 对象但不能。

我不知道如何 加入 两个表 (IssueMessage 和 IssueStatusChanged) 通过它们的标识符。

我们所做的最多 是获取所有问题的邮件帐户:

$dql = 'SELECT x, COUNT(im.id) FROM PanelBundle:Issue x LEFT JOIN PanelBundle:IssueMessages im WITH x.id = im.idIssue';

有没有人能帮帮我?

谢谢!

您想使用assication mapping;这将使 Doctrine 为您管理所有连接。

一旦到位,$issue 将始终自动提供其他关联模型,您无需担心联接。

对于下面的示例(假设您使用注释),要获取问题的消息只需获取问题对象,然后使用 $issue->getMessages();

<?php

/** @Entity */
class issue
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    // ...

    /**
     * @OneToMany(targetEntity="issueMessages", mappedBy="issue")
     */
    private $messages;

    // ...

    public function __construct()
    {
        $this->messages = new Doctrine\Common\Collections\ArrayCollection();
    }
}

/** @Entity */
class issueMessages
{
    // ...

    /**
     * @ManyToOne(targetEntity="issue", inversedBy="messages")
     * @JoinColumn(name="issue_id", referencedColumnName="id")
     */
    private $issue;

    // ...
}

我认为问题在于 DQL 语法(+ 缺少逆关系?)。

通过这样写:

SELECT x, COUNT(im.id) FROM PanelBundle:Issue x
LEFT JOIN PanelBundle:IssueMessages im WITH x.id = im.idIssue

您将根据 WITH 子句中提供的条件加入两个 "random" table。这通常应该没问题,但它可能会混淆 Hydrator 组件。

在您的情况下,您应该在 Issue 实体中配置关系的 OneToMany 端,然后编写如下内容:

SELECT x, COUNT(im.id) FROM PanelBundle:Issue x
LEFT JOIN x.issueMessages im

希望对您有所帮助!

If you using yml format for schema orm files than
first you need to write schema and mention oneToMany, manyToOne relationship with table fields & generate entity, repository class.

Than you can use join with two or more tables as below example:
Example of repository class file function:
----------------------------------------------------
public function getReportInfo($idUserDetail)
{
    $query = $this->createQueryBuilder('UR')
        ->select("UR.report_period_start_date, UR.report_period_end_date")
        ->leftJoin('UR.UserReportDetail', 'URD')
        ->andWhere('UR.id_user_detail = :id')
        ->setParameter('id', $id)
        ->orderBy('UR.report_year', 'DESC')         
        ->addOrderBy('UR.report_month', 'DESC')
        ->setMaxResults(1);

    $resultArray = $query->getQuery()->getArrayResult();

    return $resultArray;
}

You can call this function from controller action as below:
-------------------------------------------------------------
public function getUserDetailAction($idUserDetail)
{
    $em = $this->getDoctrine()->getManager();
    $userDetail = $em->getRepository(
        'DemoBundle:UserDetail')
        ->getReportInfo($idUserDetail);

    return $userDetail;
}

I hope this would be useful to you.