多对多关系中的多个联接

时间:2019-05-01 12:30:14

标签: symfony doctrine-orm symfony4

我有3个实体,用户,停车和旅行。 用户与停车有一个ManyToMany关系,而停车与voiture具有OneToMany关联。

我要做什么:

获取属于当前用户所涉及的所有停车位的汽车(票数)

我如何尝试:

使用querybuilder,但我仍然不知道如何使其工作

这是我的实体

实体用户:

<?php

/**
 * @ORM\Entity
 * @UniqueEntity(fields="username", message="Username already taken")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    public function getId()
    {
        return $this->id;
    }


    /**
     * @ORM\Column(type="string", length=191, unique=true)
     * @Assert\NotBlank()
     */
    private $username;


    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Parking", mappedBy="agents")
     */
    private $parkings;
    public function __construct()
    {
        $this->parkings = new ArrayCollection();
    }



    /**
     * @return Collection|Parking[]
     */
    public function getParkings(): Collection
    {
        return $this->parkings;
    }

    public function addParking(Parking $parking): self
    {
        if (!$this->parkings->contains($parking)) {
            $this->parkings[] = $parking;
            $parking->addAgent($this);
            return $this;
        }

        return $this;
    }

    public function removeParking(Parking $parking): self
    {
        if ($this->parkings->contains($parking)) {
            $this->parkings->removeElement($parking);
            $parking->removeAgent($this);
        }

        return $this;
    }
}

实体停车:

<?php

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

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

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\user", inversedBy="parkings")
     */
    private $agents;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Voiture", mappedBy="parking", orphanRemoval=true)
     */
    private $voitures;


    public function __construct()
    {
        $this->agents = new ArrayCollection();
        $this->voitures = new ArrayCollection();
    }

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


    /**
     * @return Collection|user[]
     */
    public function getAgents(): Collection
    {
        return $this->agents;
    }

    public function addAgent(user $agent): self
    {
        if (!$this->agents->contains($agent)) {
            $this->agents[] = $agent;
        }

        return $this;
    }

    public function removeAgent(user $agent): self
    {
        if ($this->agents->contains($agent)) {
            $this->agents->removeElement($agent);
        }

        return $this;
    }

    /**
     * @return Collection|Voiture[]
     */
    public function getVoitures(): Collection
    {
        return $this->voitures;
    }

    public function addVoiture(Voiture $voiture): self
    {
        if (!$this->voitures->contains($voiture)) {
            $this->voitures[] = $voiture;
            $voiture->setParking($this);
        }

        return $this;
    }

    public function removeVoiture(Voiture $voiture): self
    {
        if ($this->voitures->contains($voiture)) {
            $this->voitures->removeElement($voiture);
            // set the owning side to null (unless already changed)
            if ($voiture->getParking() === $this) {
                $voiture->setParking(null);
            }
        }

        return $this;
    }

}

与实体之旅

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

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

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


    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Parking", inversedBy="voitures")
     * @ORM\JoinColumn(nullable=false)
     */
    private $parking;

    /**
     * @ORM\Column(type="boolean")
     */
    private $parked;



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

    public function getMatricule(): ?string
    {
        return $this->matricule;
    }

    public function setMatricule(string $matricule): self
    {
        $this->matricule = $matricule;

        return $this;
    }



    public function getParking(): ?Parking
    {
        return $this->parking;
    }

    public function setParking(?Parking $parking): self
    {
        $this->parking = $parking;

        return $this;
    }

}

2 个答案:

答案 0 :(得分:1)

从Voiture实体开始并内部加入,使用它们之间的关联来停车和用户实体:

$queryBuilder = $this->getDoctrine()->getRepository('App:Voiture')->createQueryBuilder('v');
$queryBuilder->innerJoin('v.parking', 'p');
$queryBuilder->innerJoin('v.agents', 'a');

最后,您可以通过以下条件对关系进行过滤:

$queryBuilder->where('a.id = :userId');
$queryBuilder->setParameter("userId", 1);

$cars = $queryBuilder->getQuery()->getResult();

将条件放在$queryBuilder->innerJoin('v.agents', 'a', 'WITH', 'a.id = :userId');上,见doctrine inner join with condition

参考

答案 1 :(得分:1)

我建议在User和Parking实体之间添加一个中间实体UserParking。 因此,我们在用户和停车之间具有OneToMany关系,而在停车和用户停车之间具有OneToMany关系,而不是在用户和停车之间具有ManyToMany关系。

实体将类似于以下代码:

实体用户:

<?php

/**
 * @ORM\Entity
 * @UniqueEntity(fields="username", message="Username already taken")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    public function getId()
    {
        return $this->id;
    }


    /**
     * @ORM\Column(type="string", length=191, unique=true)
     * @Assert\NotBlank()
     */
    private $username;


    /**
     * @ORM\OneToMany(targetEntity="App\Entity\UserParking", mappedBy="agent")
     * @ORM\JoinColumn(nullable=true)
     */
    private $user_parking;

// getter and setter
}

实体停车:

<?php

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

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\UserParking", mappedBy="parking")
     * @ORM\JoinColumn(nullable=true)
     */
    private $user_parking;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Voiture", mappedBy="parking", orphanRemoval=true)
     */
    private $voitures;

// getters and setters

}

实体UserParking

/**
 * UserParking
 *
 * @ORM\Table(name="user_parking")
 * @ORM\Entity(repositoryClass="App\Repository\UserParkingRepository")
 */
class UserParking
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="user_parking")
     * @ORM\JoinColumn(nullable=false)
     */
    private $agent;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Parking", inversedBy="user_parking")
     * @ORM\JoinColumn(nullable=false)
     */
    private $parking;

    // getter and setter
}

与实体之旅

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

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

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


    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Parking", inversedBy="voitures")
     * @ORM\JoinColumn(nullable=false)
     */
    private $parking;

    /**
     * @ORM\Column(type="boolean")
     */
    private $parked;
}

因此,要获取属于当前用户所涉及的所有停车位的汽车(票数),您需要:

1-获取当前用户对象。

2-从用户对象获取UserParking数组。

3-从UserParking数组中获取Parking对象。

4-从“停车”对象中获取汽车。

代码将与此类似:

$em = $this->getDoctrine()->getManager();

/* Get user from the session */
$user = $this->getUser();

$userParkings = $user->getUserParking();
$parkings = [];
foreach ($userParkings as $item) {
    $parking = $item->getParking();
    $parkings[count($parkings)] = $parking;
}
// you can get voitures from parkings