学说加入一个有两个的表

时间:2016-02-02 10:28:13

标签: php mysql symfony doctrine-orm doctrine

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

EER

使用Doctrine (在Symfony2中)我试图获得一个对象数组,它本身包含所有 IssueMessages 和< em> IssueStatusChanged 对象但不能。

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

我们已经完成的最多是使用以下消息的帐户获取所有问题:

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

有人能帮我一把吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

您想使用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;

    // ...
}

答案 1 :(得分:1)

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.

答案 2 :(得分:0)

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

写下这个:

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

您正在根据WITH子句中提供的条件加入两个“随机”表。这应该是正常的,但它可能会混淆Hydrator组件。

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

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

希望它有所帮助!