如何从条件中获得另一个实体的结果?
问题描述:
I have two Entity. The first one is the Category and the second is the Product. They are in ManytoOne and OneToMany relation with each other.
$query = $repository->createQueryBuilder('category')->join('category.product', 'p');
if ($request->request->get("beginDate") != "") {
$query->andWhere('p.date >= :beginDate')
->setParameter('beginDate', $request->request->get("beginDate"));
}
if ($request->request->get("endDate") != "") {
$query->andWhere("p.date <= :endDate")
->setParameter('endDate', $request->request->get("endDate"));
}
$categories = $query->getQuery()->getResult();
foreach($categories as $category){
echo "Category: ".$category->getCategoryName()."<br />";
foreach($category->getProduct() as $product){
echo "Product: ".$product->getProductName()."<br />";
}
}
My problem is, when I get the products, then it prints the all products to the category. I think it's normal when you use OneToMany relation. But i would like to get those products from the categories, where the conditions are trues. Maybe i should make another querybuilder? But then i should copy the conditions. Is there other solution?
我有两个实体。 第一个是类别,第二个是产品。 它们处于ManytoOne和OneToMany之间。 p>
$ query = $ repository-&gt; createQueryBuilder('category') - &gt; join('category.product', 'p');
if($ request-&gt; request-&gt; get(“beginDate”)!=“”){
$ query-&gt; andWhere('p.date&gt; =:beginDate' )
- &gt; setParameter('beginDate',$ request-&gt; request-&gt; get(“beginDate”));
}
if($ request-&gt; request-&gt; get(“endDate”) !=“”){
$ query-&gt; andWhere(“p.date&lt; =:endDate”)
- &gt; setParameter('endDate',$ request-&gt; request-&gt; get(“endDate “));
}
$ categories = $ query-&gt; getQuery() - &gt; getResult();
foreach($ categories as $ category){
echo”Category:“。$ category-&gt; getCategoryName()。“&lt; br /&gt;”;
foreach($ category-&gt; getProduct()as $ product){
echo“Product:”。$ product-&gt; getProductName() 。“&lt; br /&gt;”;
}
}
code> pre>
我的问题是,当我拿到产品时,它会将所有产品打印到 类别。 我认为当你使用OneToMany关系时这是正常的。 但是我希望从类别中获得这些产品,条件是真实的。
我可以创建另一个查询构建器吗? 但后来我应该复制条件。 还有其他解决方案吗? p>
div>
答
Oh, it has been solved with this:
$query = $this->getDoctrine()->getEntityManager()->createQueryBuilder()
->select('category, product')
->from('ShopBundle:Categories', 'category')
->join('category.product', 'product');