简体   繁体   English

如何添加适当的“ Doctrine查询”构建器并联接表

[英]How do I add a proper Doctrine Query builder and Join a table

I am trying to build this SQL query into query builder but when adding a join, it breaks. 我正在尝试将此SQL查询构建到查询生成器中,但是在添加联接时会中断。 If I take out join it works but there are the item's in Join that id like to have access to. 如果我退出加入,则可以使用它,但是在加入中有该项目的ID可以访问。

I have tried different methods of using query builder, I have read the documentation and follow its instructions but its not working. 我尝试了使用查询生成器的其他方法,已经阅读了文档并按照其说明进行操作,但不起作用。

Here is my SQL query 这是我的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;

Here is my Query builder inside Symfony. 这是我在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();

However, I am getting an error (below) 但是,我收到一个错误(如下)

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  

What id like to do is select the Invoice table base along with the Item table so I can access both of its properties. id要做的是选择“发票”表库和“项目”表,以便我可以访问其两个属性。 I am trying to create a Symfony command that runs an SQL query, report results for items in status 2 and eventually adds it as a cronjob. 我正在尝试创建一个运行SQL查询的Symfony命令,报告状态2中项目的结果,并最终将其添加为cronjob。

Can you show code for associations in your entity? 您可以显示实体中关联的代码吗? From your question it looks like, it should be something like 从您的问题来看,它应该像

/** @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;
    // ...
}

More on associations at https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/association-mapping.html#one-to-many-bidirectional 有关关联的更多信息, 访问https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/association-mapping.html#one-to-many-bidirectional

I did not see a join in your QueryBuilder code, did you just forget it here or is that the error? 我在您的QueryBuilder代码中没有看到联接,您只是在这里忘记了联接还是那是错误? I wrote a function below how it would work in my case, but something along these line should help you. 我在下面的情况下编写了一个函数,但是遵循这些原则可以为您提供帮助。 I did not see a join condition in your plain sql so I assumed the column names are the same. 我在您的普通sql中没有看到连接条件,因此我假设列名相同。 If the Query is working but the error consists then take a look at the annotations in your entity, you probably need something like 如果查询正常但错误仍然存​​在,请查看您实体中的注释,您可能需要类似

  • @ORM\\ManyToOne(targetEntity="Invoice") @ORM \\ ManyToOne(targetEntity =“ Invoice”)
  • @ORM\\JoinColumn(name="invoice_id", referencedColumnName="id") @ORM \\ JoinColumn(name =“ invoice_id”,referencedColumnName =“ id”)

in your entities. 在您的实体中。 (Like already said by @Azhar Khattak) (就像@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM