I have two entities
Product
and Category
Product
has a manyToMany
(unidirectional) field with Category
with a jointable named product_has_category
I can find easily which Category
has any Product
but I don't know how to get the inverse...
Let's say I want to get all Product
for a certain Category
in a form, that form's field is category
so I can't get an entity field type with Product
query, otherwise it will fail.
$form
->add('category', 'entity', array(
'class' => 'AppBundle\Entity\Category',
'property' => 'name',
'query_builder' => function(EntityRepository $em) use ($product) {
return $em
->createQueryBuilder('c')
->innerJoin('AppBundle\Entity\Product', 'p', 'WITH', 'p.id = :product_id')
->setParameter('product_id', $product->getId())
;
},
'multiple' => true
))
;
Of course this doesn't work, but you get the idea of what I want to do. As Category
doesn't have any mapped field with Product
(because it is an unidirectional mapping), I can't find easy thoose products...
The middle table doesn't has an entity, because we don't need it, it's just a mysql table.
Running a MySQL query would be this easy, but we need it to be inside a QueryBuilder because we will use it in forms.
SELECT c.name
FROM category c
INNER JOIN product_has_category pc ON pc.category_id = e.id
INNER JOIN product p ON pc.product_id = p.id
WHERE p.id = 10
;
This, of course returns me exactly what I want, because on MySQL I do have access to the middle table so I can join everything.. but, QueryBuilder? I don't know
I've tried this but I just got everything freezed (over 7M records fetched I guess)
$em
->createQueryBuilder('c')
->select('c')
->innerJoin('AppBundle\Entity\Product', 'p', 'WITH', '1 = 1')
->innerJoin('p.categories', 'c')
->where('p.id = :product_id')
->setParameter('product_id', $product->getId())
;
I think it is not duplicated because other question doesn't include a QueryBuilder
solution/question, and some people may be confused about how to do so.