查询有问题。我有3个定义如下的实体:
class Category
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
//...
/**
* @var Product[]
*
* @ORM\ManyToMany(targetEntity="App\Entity\Product", mappedBy="categories")
*/
private $products;
//...
}
class Product
{
/**
* @var int
*
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
* @ORM\Column(type="integer")
*/
private $id;
//...
/**
* @var Collection
*
* @ORM\ManyToMany(targetEntity="App\Entity\Category", inversedBy="products")
* @ORM\JoinTable(name="product_category",
* joinColumns={
* @ORM\JoinColumn(name="id_product", referencedColumnName="id", nullable=false)
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="id_category", referencedColumnName="id", nullable=false)
* }
* )
*/
private $categories;
/**
* @var Provider
*
* @ORM\ManyToOne(targetEntity="App\Entity\Provider", inversedBy="products")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="id_provider", referencedColumnName="id", nullable=false)
* })
*/
private $provider;
//...
}
class Provider
{
/**
* @var int
*
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
* @ORM\Column(type="integer")
*/
private $id;
//...
/**
* @var Product[]
*
* @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="provider", orphanRemoval=true, cascade={"all"})
*/
private $products;
//...
}
我想查询供应商管理的所有产品类别。所以我试试这个:
class CategoryRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Category::class);
}
public function findByProvider(Provider $provider)
{
$qb = $this->createQueryBuilder('c');
return $qb->leftJoin('c.products', 'p')
->addSelect('p')
->andWhere('p.provider = :provider')
->setParameter('provider', $provider)
->addOrderBy('c.name')
->getQuery()
->getResult();
}
}
但是,尽管提供者拥有许多产品,但我总是有一个空洞的结果。 请我应该如何实现此查询。谢谢