[英]Doctrine join a table with two
早上好 ,如下圖所示,我鏈接了一些表格。
我正在嘗試使用Doctrine (在Symfony2中)來獲取一個對象Issue數組,該數組本身包含所有IssueMessages和IssueStatusChanged對象,但不能。
我不知道我該怎么做,通過它們的標識符來連接兩個表(IssueMessage和IssueStatusChanged)來。
我們要做的最重要的事情是使用具有以下消息的帳戶來獲取“所有問題”:
$dql = 'SELECT x, COUNT(im.id) FROM PanelBundle:Issue x LEFT JOIN PanelBundle:IssueMessages im WITH x.id = im.idIssue';
有人可以幫我嗎?
謝謝!
您想使用輔助映射 ; 這將使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;
// ...
}
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.
我認為問題出在DQL語法中(+缺少逆關系?)。
通過這樣寫:
SELECT x, COUNT(im.id) FROM PanelBundle:Issue x
LEFT JOIN PanelBundle:IssueMessages im WITH x.id = im.idIssue
您正在根據WITH子句中提供的條件連接兩個“隨機”表。 通常應該可以,但是可能會使Hydrator組件混亂。
在您的情況下,您應該在Issue
實體中配置關系的OneToMany
端,然后編寫如下代碼:
SELECT x, COUNT(im.id) FROM PanelBundle:Issue x
LEFT JOIN x.issueMessages im
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.