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

时间:2019-06-15 16:50:00

标签: php symfony symfony4 query-builder

我正在尝试学习Symfony。今天,我关注The associations tutorial.,因此决定做出一个小型应用,例如房屋,厨房,卧室和橱柜。我(尝试过;-))使用draw.io制作了一个小的类图,为您提供了一个更好的主意。

This is it

因此,一栋房子基本上可以有多个卧室和多个厨房。每个厨房可以有多个橱柜。房子有一个ID和一个名字。卧室和厨房也是如此。橱柜具有id shopUrl,并且还通过外键(account_id)链接到其父级Kitchen。 我还使用外键(house_id)将厨房和卧室链接到房屋。因此,我按照本教程创建了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资源库为空(又称:仅包含从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);
        }
    }

并且Bedroom存储库也为空。

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;
        }

    }

与其他实体相比,内阁有一些逻辑(这是我实际需要帮助的地方)。由于“卧室”和“厨房”与一所房屋相关联,因此我想给一个“卧室”,然后查找与“卧室”与同一个房屋相关联的所有厨房,然后返回这些厨房拥有的所有橱柜。我知道这似乎是不合逻辑的,但是我发现为时已晚,无法提出另一个概念。我当前的代码无法正常工作,因为我不确定这是否可行,并且因为此刻我觉得太复杂了。但是我把这作为内阁回购的内容:


    <?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,并且任何地方都没有显示错误,但是querybuilder当然不会返回任何内容。我该如何解决?我找不到任何问题来尝试实现我的目标。

我手动将数据添加到数据库中,因此那里有数据。使用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 815关联的Bedroom ID 555。然后应从此处选择与该house_id关联的所有Kitchen,因此255。最后,应返回ID为188的文件柜。

编辑:运行bin/console doc:sch:val时,我会得到以下提示:

`映射

[确定]映射文件正确。

数据库

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

3 个答案:

答案 0 :(得分:2)

在symfony的调试栏中,您可能会看到一些教义错误。这些将不会显示在PHPStorm中。您需要将$kitchen$bedroom重命名为其复数形式$kitchens$bedrooms(并更改获取器/设置器以匹配),因为这是您在所有权中定义事物的方式学说关系的另一面。

比存储库方法更简单的方法是在控制器中执行所需的操作,以使主义能够完成繁重的工作:

$cabinets = [];

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

答案 1 :(得分:2)

您的代码中有几个小问题,以后会更多。

这是\ 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的卧室实体,上面的代码返回以下内容(格式为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);
}

答案 2 :(得分:0)

首先,我认为是因为您同时在这两个实体中加入

...
            ->join('cabinet.bedroom', 'bedroom')
            ->join('cabinet.kitchen', 'kitchen')
...

并且因为这将与INNER JOIN一起使用,所以它要求卧室和厨房橱柜都必须装有机舱。

为此,几乎没有解决方案可以解决:

  • 正确的方法是重新设计您的实体。我认为使用Doctrine inheritance
  • 可能并不困难
  • 您可以将连接更改为左,因此关系不是强制性的(可以工作,但是由于设计错误,通常情况下它不是很好的解决方案)