1

I hava relations Many-to-Many with Product entity and Feature entity Product entity:

/**
 * @ORM\ManyToMany(targetEntity="Feature")
 * @ORM\JoinTable(name="Product_Feature",
 *      joinColumns={@ORM\JoinColumn(name="Product_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="Feature_id", referencedColumnName="id")}
 *      )
 */
private $features;

Feature entity:

/**
 * @ORM\ManyToMany(targetEntity="Product", mappedBy="features")
 * @ORM\OrderBy({"position" = "ASC"})
 */
private $products;

ProductRepository.php:

public function updateFeatures($id, $featuresIds)
    {
        return $this->getEntityManager()->createQueryBuilder()
                ->update('TestCatalogBundle:Product', 'p')
                ->set('p.features', ':features')
                ->where('p.id = :id')
                ->setParameter('features', $featuresIds)
                ->setParameter('id', $id)
                ->getQuery()
                ->getResult();
    }

But when I call updateFeatures I get error:

features = :features': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected

How can I update Product_Feature table? Also I can't delete all features from Product_Feature by product's id.
I changed my controller in next way:

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

    $features = $em->getRepository('TestCatalogBundle:Feature')->findBy(array('id' => $featureIds));
    $product = $em->getRepository('TestCatalogBundle:Product')->find($id);

    $product->getFeatures()->clear();
    foreach ($features as $feature) {
        $product->addFeature($feature);
    }
    $em->persist($product);
    $em->flush();

But if I use native sql I need 2 queries for deleting features and insert new features. But here I need 2 select queries. Maybe I made this task wrong?

Dmitro
  • 1,489
  • 4
  • 22
  • 40
  • **Answer**: Please refer to the answer I made on http://stackoverflow.com/a/35445060/2423563 – SudarP Feb 16 '16 at 23:45

1 Answers1

2

You're doing it the wrong way. You should read this chapter of the documentation: Working with associations. You should add an "inversedBy" keyword in the $features field of the Product class.

When you have a bi-directional many-to-many relation, the usual way to do this is:

$product->getFeatures()->add($feature); // Or $product->setFeatures($features);
$feature->getProducts()->add($product);
$em->persist($product);
$em->persist($feature);
$em->flush();
tzi
  • 8,719
  • 2
  • 25
  • 45
Nanocom
  • 3,696
  • 4
  • 31
  • 46