I have the following entities.
Entity Product:
namespace App\Model;
use Nette\Object;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @ORM\Entity
*/
class Product extends Object
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
* @var int
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Category")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id", onDelete="SET NULL")
* @var int
*/
private $category;
/**
* @ORM\OneToOne(targetEntity="Image", cascade={"persist", "remove"})
* @var Image
*/
private $image;
/**
* @ORM\OneToOne(targetEntity="Image", cascade={"persist", "remove"})
* @ORM\JoinColumn(nullable=true, onDelete="SET NULL")
* @var Image
*/
private $backgroundImage;
/**
* @ORM\ManyToOne(targetEntity="Layer")
* @ORM\JoinColumn(name="methodOfPreparing_id", referencedColumnName="id", onDelete="SET NULL")
* @var Layer|NULL
*/
private $methodOfPreparing;
}
Entity Layer:
/**
* @ORM\Entity
*/
class Layer extends Object
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
* @var int
*/
private $id;
/**
* @ORM\OneToMany(targetEntity="State", mappedBy="layer", indexBy="position", cascade={"persist", "remove"})
* @var ArrayCollection
*/
private $states;
/**
* @ORM\Column(type="string")
* @var string
*/
private $name;
/**
* @ORM\Column(type="integer")
* @var int
*/
private $position;
}
Entity State:
/**
* @ORM\Entity
*/
class State extends Object
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
* @var int
*/
private $id;
/**
* @ORM\Column(type="string")
* @var string
*/
private $name;
/**
* @ORM\ManyToOne(targetEntity="Layer", inversedBy="states")
* @ORM\JoinColumn(name="layer_id", referencedColumnName="id", onDelete="CASCADE")
* @var Layer
*/
private $layer;
/**
* @ORM\Column(type="integer")
* @var int
*/
private $position;
/**
* @ORM\Column(type="integer", columnDefinition="int(1) NOT NULL")
* @var bool
*/
private $active;
}
skeleton query:
SELECT Product
FROM product
LEFT JOIN
(SELECT Layer, State
FROM layer
INNER JOIN state ON layer.id = state.layer_id
WHERE state.active = 1
) sub
ON sub.id = product.methodOfPreparing_id
I need to create a DQL query using the query builder. It is possible left join subquery?
You can do LEFT JOIN subqueries in DQL using a WITH clause as the JOIN criteria.
E.g.,
... or ...
... and the like.
Here are working samples from a codebase I work on:
... and ...