Search code examples
phpsymfonydoctrineentitysymfony4

How can I remove entity relations (Symfony 4)?


My table fields:

id  name
1   cat
2   dog 
3   frog

My table productgroup

id  name
1   animals
2   food 
3   colors

My table fields_productgroup

fields_1  productgroup_1
1         1
2         1
3         2

What I want to do now is remove the relation of frog to colors.

My Controller:

public function remove($entity, $id, $relation, $relation_id, Request $request)
{
    $obj = $this->getDoctrine()->getRepository(fields::class)->findOneBy(['id' => $id]);
    $entity_id = $obj->getId();

    $enity_reference = $entityManager->getReference(fields::class, $entity_id);
    $relation_reference = $entityManager->getReference(productgroup::class, $relation_id);

    $func = 'removeProductgroup';
    $enity_reference->$func($relation_reference);

    $entityManager->persist($enity_reference);
    $entityManager->persist($relation_reference);
    $entityManager->flush();
    $response = new Response();
    $response->send();
    return $response;
}

This is the function in my fields entity:

public function removeProductgroup(Productgroup $productgroup)
{
    $this->productgroup->removeElement($productgroup)

    return $this;
}

But I get the error message:

syntax error, unexpected 'return' (T_RETURN)


Solution

  • If the code in your answer is exactly the code you use, then you have a syntax error in the following snippet:

    public function removeProductgroup(Productgroup $productgroup)
    {
        $this->productgroup->removeElement($productgroup) // missing semicolon here
    
        return $this;
    }

    It should obviously be:

    public function removeProductgroup(Productgroup $productgroup)
    {
        $this->productgroup->removeElement($productgroup);
    
        return $this;
    }

    You have to finish a statement line with a semicolon. The interpreter sees the keyword return and throws syntax error. For PHP the white space makes no difference, so it interprets the code as:

    $this->productgroup->removeElement($productgroup) return $this;