0

I have two tables in the Authors and Books database. Since the relationship is many to many, I created a third table (summary). I can't organize data deletion. I'm trying to delete the book, but because of the foreign key, Symfony won't let me do it.

/**
 * @Route("/{id}", name="bookRemoveAjax", methods={"DELETE"})
 */
public function bookRemoveAjax(Request $request, int $id)
{
    $em = $this->getDoctrine()->getManager();
    $book = $em->getRepository(Books::class)->find($id);
    if($book) {

        $em->remove($book);
        $em->flush();
        return $this->json([
            "message" => "ok"
        ], 200);
    }
    else {
        return $this->json("error", 500);
    }
}

Entity:

class Books
/**
 * @ORM\Id
 * @ORM\GeneratedValue
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=255)
 */
private $name;

/**
 * @ORM\Column(type="string", length=255)
 */
private $photo;
/**
 * @var ArrayCollection
 * @ORM\ManyToMany(targetEntity="Authors", inversedBy="books")
 * @ORM\JoinTable(name="authors_books")
 * @ORM\JoinColumn(name="authors_id", referencedColumnName="id", onDelete="CASCADE")
 */
private $authors;

public function __construct() {
    $this->authors = new ArrayCollection();
}

public function getAuthors(): PersistentCollection
{
    return $this->authors;
}

public function removeAuthors (Authors $author): self
{
    if ($this->authors->contains($author)) {
        $this->authors->removeElement($author);
    }
    return $this;
}

I can't delete first from authors_books since Entity is not provided. I wanted to use on Delete="CASCADE", but I don't understand how to use it correctly

yivi
  • 42,438
  • 18
  • 116
  • 138

1 Answers1

-2

you have to remove the book in the table authors_book first

sbabti zied
  • 784
  • 5
  • 17