如何使用查询生成器在 Symfony 4 中的一个外部 ID 上加入多个实体?

How to join multiple entities on a foreign ID in Symfony 4 using a query builder?

我正在努力学习 Symfony。今天我在关注 The associations tutorial. 我决定制作一个小应用程序,包括房屋、厨房、卧室和橱柜。我(试图 ;-) )使用 draw.io 制作了一个小的 Class 图表来给你一个更好的主意。

所以基本上一个房子可以有多个卧室和多个厨房。每个厨房可以有多个橱柜。众议院有一个 ID 和一个名字。卧室和厨房也是如此。内阁有 id、shopUrl 并且还通过外键 (account_id) linked 到其父 Kitchen。 我还使用外键 (house_id) link 厨房和卧室到房子。所以我按照教程创建了 House 实体:

    <?php

    namespace App\Entity;

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

    /**
     * @ORM\Entity(repositoryClass="App\Repository\HouseRepository")
     */
    class House implements \JsonSerializable
    {

        /**
         * @ORM\OneToMany(targetEntity="App\Entity\Kitchen", mappedBy="house")
         */
        private $kitchen;

        /**
         * @ORM\OneToMany(targetEntity="App\Entity\Bedroom", mappedBy="house")
         */
        private $bedroom;    

        /**
         * House constructor
         */
        public function __construct()
        {
            $this->kitchen = new ArrayCollection();
            $this->bedroom = new ArrayCollection();
        }

        /**
         * @return Collection|Kitchen[]
         */
        public function getKitchen(): Collection
        {
            return $this->kitchen;
        }

        /**
         * @return Collection|Bedroom[]
         */
        public function getBedroom(): Collection
        {
            return $this->bedroom;
        }


        /**
         * @ORM\Id()
         * @ORM\GeneratedValue()
         * @ORM\Column(type="integer")
         */
        private $id;

        /**
         * @ORM\Column(type="string", length=255)
         */
        private $name;

        public function getId(): ?int
        {
            return $this->id;
        }

        public function getName(): ?string
        {
            return $this->name;
        }

        public function setName(string $name): self
        {
            $this->name = $name;

            return $this;
        }

        public function jsonSerialize()
        {
            return get_object_vars($this);
        }
    }

House 存储库为空(a.k.a:仅包含 Symfony 自动生成的代码):

    <?php

    namespace App\Repository;

    use App\Entity\House;
    use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
    use Symfony\Bridge\Doctrine\RegistryInterface;

    /**
     * @method House|null find($id, $lockMode = null, $lockVersion = null)
     * @method House|null findOneBy(array $criteria, array $orderBy = null)
     * @method House[]    findAll()
     * @method House[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
     */
    class HouseRepository extends ServiceEntityRepository
    {
        public function __construct(RegistryInterface $registry)
        {
            parent::__construct($registry, House::class);
        }

    }

Bedroom 实体是这样的:

    <?php

    namespace App\Entity;

    use Doctrine\ORM\Mapping as ORM;

    /**
     * @ORM\Entity(repositoryClass="App\Repository\BedroomRepository")
     */
    class Bedroom implements \JsonSerializable
    {

        /**
         * @ORM\ManyToOne(targetEntity="App\Entity\House", inversedBy="bedroom")
         */
        private $house;

        public function getHouse(): House
        {
            return $this->house;
        }

        public function setHouse(House $house): self
        {
            $this->house = $house;

            return $this;
        }


        /**
         * @ORM\Id()
         * @ORM\GeneratedValue()
         * @ORM\Column(type="integer")
         */
        private $id;

        /**
         * @ORM\Column(type="string", length=255)
         */
        private $name;

        public function getId(): ?int
        {
            return $this->id;
        }

        public function getName(): ?string
        {
            return $this->name;
        }

        public function setName(string $name): self
        {
            $this->name = $name;

            return $this;
        }

        public function jsonSerialize()
        {
            return get_object_vars($this);
        }
    }

卧室存储库也是空的。

Kitchen 实体具有以下代码:

    <?php

    namespace App\Entity;

    use Doctrine\ORM\Mapping as ORM;

    /**
     * @ORM\Entity(repositoryClass="App\Repository\KitchenRepository")
     */
    class Kitchen implements \JsonSerializable
    {


        /**
         * @ORM\OneToMany(targetEntity="App\Entity\Cabinet", mappedBy="kitchen")
         */
        private $cabinet;

        /**
         * Kitchen constructor
         */
         public function __construct()
        {
            $this->cabinet= new ArrayCollection();
        }

        /**
         * @return Collection|Cabinet[]
         */
        public function getCabinet(): Collection
        {
            return $this->cabinet;
        }


        /**
         * @ORM\ManyToOne(targetEntity="App\Entity\House", inversedBy="kitchen")
         */
        private $house;

        public function getHouse(): House
        {
            return $this->house;
        }

        public function setHouse(House $house): self
        {
            $this->house = $house;

            return $this;
        }

        /**
         * @ORM\Id()
         * @ORM\GeneratedValue(strategy="UUID")
         * @ORM\Column(type="integer")
         */
        private $id;

        /**
         * @ORM\Column(type="string", length=255)
         */
        private $name;

        public function getId(): int
        {
            return $this->id;
        }

        public function getName(): string
        {
            return $this->name;
        }

        public function setName(string $name): self
        {
            $this->name = $name;

            return $this;
        }

        public function jsonSerialize()
        {
            return get_object_vars($this);
        }
    }

并且 Kitchen 存储库也是空的。 最后,cabinet 由以下内容组成:

    <?php

    namespace App\Entity;

    use DateTime;
    use Doctrine\ORM\Mapping as ORM;

    /**
     * @ORM\Entity(repositoryClass="App\Repository\CabinetRepository")
     */
    class Cabinet
    {
        /**
         * @ORM\Id()
         * @ORM\GeneratedValue()
         * @ORM\Column(type="integer")
         */
        private $id;

        /**
         * @ORM\Column(type="string", length=255)
         */
        private $shopUrl;

        private $account_id;

        /**
         * @ORM\ManyToOne(targetEntity="Kitchen", inversedBy="cabinet")
         */
        private $kitchen;

        /**
         * Cabinet constructor.
         * @param string $shopUrl
         * @param Kitchen $kitchen
         * @param int $id
         */
        public function __construct(string $shopUrl, Kitchen $kitchen = null, int $id = null)
        {
            $this->shopUrl = $shopUrl;
            $this->kitchen = $kitchen;
            $this->id = $id;
        }

        public function setId(int $id): self
        {
            $this->id = $id;

            return $this;
        }

        public function getId(): int
        {
            return $this->id;
        }


        public function getShopUrl(): string
        {
            return $this->shopUrl;
        }

        public function getKitchen(): Kitchen
        {
            return $this->kitchen;
        }

        public function setKitchen(Kitchen $kitchen): self
        {
            $this->kitchen = $kitchen;
            $this->account_id = $kitchen->getId();
            return $this;
        }

        public function setAccount_id(int $account_id): self
        {
            $this->account_id = $account_id;

            return $this;
        }

        public function getAccount_id(): int
        {
            return $this->account_id;
        }

    }

与其他实体相比,内阁有一些逻辑(这是我真正需要帮助的地方)。由于 Bedroom 和 Kitchen 与房子相关联,我想给出一个卧室,然后查找与卧室相同的房子相关联的所有厨房,然后 return 这些厨房拥有的所有橱柜。我知道这可能看起来不合逻辑,但我发现这个太晚了,无法提出另一个概念。我当前的代码不起作用,因为我不确定这是否可行,而且目前我无法掌握它有点太复杂了。但是我有这个作为内阁回购的内容:


    <?php

    namespace App\Repository;

    use App\Entity\Bedroom;
    use App\Entity\House;
    use App\Entity\Cabinet;
    use App\Entity\Kitchen;
    use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
    use Symfony\Bridge\Doctrine\RegistryInterface;

    /**
     * @method Cabinet|null find($id, $lockMode = null, $lockVersion = null)
     * @method Cabinet|null findOneBy(array $criteria, array $orderBy = null)
     * @method Cabinet[]    findAll()
     * @method Cabinet[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
     */
    class CabinetRepository extends ServiceEntityRepository
    {
        public function __construct(RegistryInterface $registry)
        {
            parent::__construct($registry, Cabinet::class);
        }

        public function findByBedroom(Bedroom $bedroom) //use joins??
        {
            return $this->createQueryBuilder('cabinet')
                ->join('cabinet.bedroom', 'bedroom')
                ->join('cabinet.kitchen', 'kitchen')
                ->addSelect('cabinet')
                ->andWhere('cabinet.bedroom = :idBedroom')
                ->setParameter('idBedroom', $bedroom->getId())
                ->orderBy('time', 'ASC')
                ->getQuery()
                ->getResult();
        }
    }

我正在使用 PHPStorm,没有任何错误显示,当然,查询构建器没有 return 任何东西。我该如何解决?我找不到任何试图实现我想要做的事情的问题。

我手动向数据库添加了数据,所以里面有数据。使用 Sequel Pro 我可以看到关系。数据(就我而言)很好。 queryBuilder 是错误所在。

带有一些数据的示例:

这是卧室数据:

id     name              house_id  
325    bigBedroomOne     1666   
815    smallBedroomOne   555   
902    bigBedroomTwo     1666

这是房屋数据:

id     name          
1666   bigHouse      
555    smallHouse      

这是厨房数据:

id   name              house_id
1    bigKitchen        1666
2    smallKitchen      555
55   mediumKitchen     555

最后,这是橱柜数据:

id  shopUrl    account_id
1   ur.l       55
88  co.m       2
33  ne.t       1

所以在这个例子中,我想插入与 house_id 555 关联的卧室 ID 815。然后应从那里选择与 house_id 关联的所有厨房,因此 255。最后,id为188的柜子应该returned.

编辑:当 运行 bin/console doc:sch:val 我回来了:

`映射

[确定]映射文件正确。

数据库

[确定] 数据库模式与映射文件同步。`

首先我想是因为你在这个

中同时加入了两个实体
...
            ->join('cabinet.bedroom', 'bedroom')
            ->join('cabinet.kitchen', 'kitchen')
...

并且因为这将与 INNER JOIN 一起使用,所以要求卧室和厨柜都需要 cabined。

为此,解决方案很少:

  • 正确的方法是重新设计您的实体。我觉得用起来可能不难 Doctrine inheritance
  • 您可以将连接更改为左侧,因此关系不是强制性的(会起作用,但由于设计错误,通常不是很好的解决方案)

在 symfony 的调试栏中,您可能会看到一些教义错误。这些不会出现在 PHPStorm 中。您需要将 $kitchen$bedroom 重命名为它们的复数形式 $kitchens$bedrooms (并更改您的 getters/setters 以匹配),因为这是您定义事物的方式你的学说关系的拥有方。

比存储库方法更简单的方法是在控制器中执行您想做的事情,让 doctrine 完成您的繁重工作:

$cabinets = [];

$house = $bedroom->getHouse();
$kitchens = $house->getKitchens();
foreach ($kitchens as $kitchen) {
    $kitchenCabinets = $kitchen->getCabinets();
    $cabinets = array_merge($cabinets, $kitchenCabinets);
}

您的代码中有几个小问题,稍后会详细介绍。

这里是 \App\Repository\CabinetRepository::findByBedroom:

    public function findByBedroom(Bedroom $bedroom) //use joins??
    {
        return $this->createQueryBuilder('cabinet')
            ->join('cabinet.kitchen', 'kitchen')
            ->join('kitchen.house', 'house')
            ->join('house.bedroom', 'bedroom')
            ->addSelect('cabinet')
            ->andWhere('bedroom = :bedroom')
            ->setParameter('bedroom', $bedroom)
            ->getQuery()
            ->getResult();
    }

对于 ID 为 815 的卧室实体,上面的代码 returns 以下(格式为 symfony/var-dumper 会这样做):

array:2 [▼
  0 => Cabinet {#387 ▼
    -id: 88
    -shopUrl: "co.m"
    -account_id: null
    -kitchen: Kitchen {#354 ▼
      +__isInitialized__: false
      -cabinet: null
      -house: null
      -id: 2
      -name: null
       …2
    }
  }
  1 => Cabinet {#364 ▼
    -id: 1
    -shopUrl: "ur.l "
    -account_id: null
    -kitchen: Kitchen {#370 ▼
      +__isInitialized__: false
      -cabinet: null
      -house: null
      -id: 55
      -name: null
       …2
    }
  }
]

注意:由于延迟加载,房屋引用为空。

所以,你的代码中的小问题:

  1. 您在 CabinerRepository 中的查询进行了错误的连接。对于正确的连接,请参见上面的代码。

  2. 该查询引用了未知字段 time。我已删除该引用。

  3. 并且还使用卧室 ID 而不是卧室实体。

  4. 你的Kitchen.php不完整,引用了Collection和ArrayCollection类,但是没有对应的use指令。只需在 namespace 之后添加 class 之前:

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

更新:这里是获取存储库引用的方法:

public function myControllerAction(/* other parameters */, CabinetRepository $cabRepo)
{
    $cabinet = $cabRepo->find($id);
    // OR, if you don't want to add parameter for some reason:
    $cabRepo = $this->getDoctrine()->getRepository(Cabinet::class);
    $cabinet = $cabRepo->find($id);
}