本文介绍了Symfony / Doctrine:选择多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Symfony和Doctrine还是很陌生,我找不到解决问题的方法。

Im pretty new to Symfony and Doctrine and I can't find a solution to my problem.

我有一个名为 transactional的数据库表和一个叫 customer 的客户。在 transactional 表中,是 customer 表的外键。现在,我想从两个表中获取所有数据。但是Customer字段都设置为null。

I have a database table called transactional and one called customer. In the transactional table is a foreign key to the customer table. Now I want to get all the data from both tables. But the Customer fields are all set to null.

这是 transactional php对象中的外键:

Here is the foreign key in the transactional php object:

交易型

/**
 * @var \AppBundle\Entity\Customer
 *
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Customer")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="fk_customer", referencedColumnName="id")
 * })
 */
private $fkCustomer;

教义查询:

$em = $this->getDoctrine()->getManager();
$transactions = $em->getRepository('AppBundle:Transactional')->findAll();
dump($transactions);

结果:

0 => Transactional {#483 ▼
-id: 1
-date: DateTime @1510873200 {#493 ▶}
-fkCustomer: Customer {#566 ▼
  +__isInitialized__: false
  -id: 1
  -gender: null
  -firstname: null

非常感谢您的时间和帮助。 =)

Thank you very much for your time and help. =)

推荐答案

这是学说的延迟加载。

That is doctrines lazy loading.

访问事务对象的客户属性后,相关信息将被加载。

Once you access the customer property of your Transactional object the related information will be loaded.

这不是理想的选择,但是如果您要遍历许多事务条目,因为每个客户对象都将通过单个查询加载。

This isn't ideal however if you iterate over many transactional entries since every customer object will be loaded through a single query.

您可以通过将fetchMode设置为 EAGER 来解决此问题,例如:

You can solve this either by setting the fetchMode to EAGER like:

/**
 * @var \AppBundle\Entity\Customer
 *
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Customer", fetch="EAGER")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="fk_customer", referencedColumnName="id")
 * })
 */
private $fkCustomer;

应完全填充客户数据,而不是使用代理对象。

which should populate the customer data completely instead of using a proxy object.

另一种方法是通过自定义存储库方法加载交易项目,该方法显式连接客户数据。
例如,通过为 Transactional 创建自定义存储库并添加如下功能:

Another way would be loading the transactional items through a custom repository method that explicitly joins the customer data.For example by creating a custom repository for Transactional and add a funciton like this:

public function load()
{
    $qb = $this->_em->createQueryBuilder();
    $qb->select('t, c')
        ->from('AppBundle:Transactional','t')
        ->join('t.fkCustomer', 'c');

    return $qb->getQuery()->execute();
}

如何创建自定义存储库可以在文档中找到:

how to create a custom repository can be found in the docs: https://symfony.com/doc/3.3/doctrine/repository.html

这篇关于Symfony / Doctrine:选择多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:02