[英]How do I add a proper Doctrine Query builder and Join a table
我正在嘗試將此SQL查詢構建到查詢生成器中,但是在添加聯接時會中斷。 如果我退出加入,則可以使用它,但是在加入中有該項目的ID可以訪問。
我嘗試了使用查詢生成器的其他方法,已經閱讀了文檔並按照其說明進行操作,但不起作用。
這是我的SQL查詢
SELECT * FROM invoice i
JOIN item it
WHERE i.created_at >= '2019-03-26 08:00:00' and
i.created_at <= '2019-03-26 08:05:00' and i.status=2;
這是我在Symfony中的查詢生成器。
/** @var \Doctrine\ORM\EntityManager $em *
$em = $container->get('doctrine')->getManager();
$em->getConnection()->getConfiguration()->setSQLLogger(null);
/** @var EntityRepository $repository */
$repository = $em->getRepository('GivingBundle:Invoice');
/** @var QueryBuilder $qb */
$qb = $repository->createQueryBuilder('i');
$qb->join('i.item', 'it')
->Where($qb->expr()->between('i.created_at', ':starts_at', ':ends_at'))->andWhere('i.status = 1')
->setParameter('starts_at',$startsAt,\Doctrine\DBAL\Types\Type::DATETIME)
->setParameter('ends_at', $endsAt,\Doctrine\DBAL\Types\Type::DATETIME)
;
$query = $qb->getQuery();
$results = $query->getResult();
但是,我收到一個錯誤(如下)
Doctrine\ORM\Query\QueryException]
[Semantical Error] line 0, col 66 near 'it WHERE (i.created_at':
Error: Class KCM\GivingBundle\Entity\Invoice has no association
named item
id要做的是選擇“發票”表庫和“項目”表,以便我可以訪問其兩個屬性。 我正在嘗試創建一個運行SQL查詢的Symfony命令,報告狀態2中項目的結果,並最終將其添加為cronjob。
您可以顯示實體中關聯的代碼嗎? 從您的問題來看,它應該像
/** @Entity */
class Invoice
{
// ...
/**
* This is the inverse side.
* @OneToMany(targetEntity="Items", mappedBy="invoice")
*/
private $items;
// ...
public function __construct() {
$this->items= new ArrayCollection();
}
}
/** @Entity */
class Items
{
// ...
/**
* This is the owning side.
* @ManyToOne(targetEntity="Invoice", inversedBy="items")
* @JoinColumn(name="invoice_id", referencedColumnName="id")
*/
private $invoice;
// ...
}
有關關聯的更多信息, 請訪問https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/association-mapping.html#one-to-many-bidirectional
我在您的QueryBuilder代碼中沒有看到聯接,您只是在這里忘記了聯接還是那是錯誤? 我在下面的情況下編寫了一個函數,但是遵循這些原則可以為您提供幫助。 我在您的普通sql中沒有看到連接條件,因此我假設列名相同。 如果查詢正常但錯誤仍然存在,請查看您實體中的注釋,您可能需要類似
在您的實體中。 (就像@Azhar Khattak已經說過的那樣)
public function findInvoice($dateFrom, $dateTo)
{
$qb = $this->em->createQueryBuilder();
$qb->select('i')
->from(Invoice::class, 'i')
->join(Item::class, 'it', Join::WITH, 'i.created_at = it.created_at')
->where($queryBuilder->expr()->between('r.created_at', ':datefrom', ':dateto'))
->andWhere($qb->expr()->eq('i.status', 1))
->setParameters(['datefrom' => $dateFrom, 'dateto' => $dateTo])
return $qb->getQuery()->getResult();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.