为什么Doctrine2为findAll()做一个INNER JOIN?

时间:2015-06-24 18:19:28

标签: php mysql doctrine-orm doctrine inner-join

我有一个UserCompany实体。每个User都属于Company。这是我的实体(缩短):

<?php

namespace App\Model\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**  
 * @ORM\Table(name="user")
 */
class User
{
    /** 
     * @ORM\Id
     * @ORM\Column(type="integer", name="user_id")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(length=200)
     */
    private $email;

    /**
     * @ORM\ManyToOne(targetEntity="Company", inversedBy="users", fetch="EAGER")
     * @ORM\JoinColumn(name="company_id", referencedColumnName="company_id", nullable=false)
     */
    private $company;

    // And a bunch of getters/setters

<?php

namespace App\Model\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/** 
 * @ORM\Table(name="company")
 */
class Company
{
    /** 
     * @var int
     *
     * @ORM\Id
     * @ORM\Column(type="integer", name="company_id", options={"unsigned":1})
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(length=100, unique=true)
     */
    private $name = "";

    /**
     * @var Doctrine\Common\Collections\ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="User", mappedBy="company", cascade={"persist", "remove"}, fetch="LAZY")
     */
    private $users;

    // getters/setters

当我测试我的生产代码时,我忘记将公司添加到公司表中。所以,当我做一个基本的$entityManager->getRepository('App/Model/Entity/User')->findAll();以确保我的数据库正确连接时,它返回一个空数组,即使我有一个用户在那里。

我挖了一下,找到它输出的SQL,就是这样:

SELECT 
    t0.user_id AS user_id1, 
    t0.email AS email2, 
    t0.company_id AS company_id3, 
    t10.company_id AS company_id5, 
    t10.name AS name6 FROM user t0 
INNER JOIN company t10 
ON t0.company_id = t10.company_id

我意识到INNER JOIN是我没有得到任何用户的原因。现在我好奇是什么导致Doctrine使用INNER JOIN?是由于nullable=false对于User实体中的公司属性还是其他什么?

0 个答案:

没有答案