Why does Doctrine2 do an INNER JOIN for findAll()?

大城市里の小女人 提交于 2019-12-13 01:54:05

问题


I have a User and Company entity. Each User belongs to a Company. Here are my entities (shortened):

<?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

When I was testing my production code, I forgot to add a company to the company table. So, when I did a basic $entityManager->getRepository('App/Model/Entity/User')->findAll(); to make sure my database was connecting correctly, it returned an empty array, even though I had a user in there.

I dug a little bit to find the SQL it was outputting, which was this:

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

I realized the INNER JOIN was the reason I wasn't getting any users. Now I'm curious what causes Doctrine to use the INNER JOIN? Is it due to nullable=false for the company attribute in the User entity, or something else?

来源:https://stackoverflow.com/questions/31034078/why-does-doctrine2-do-an-inner-join-for-findall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!