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
My Answer:
"/book/delete/{id}", name="delete_book")_*/
public function deleteBook($id)
{
$entityManager = $this->getDoctrine()->getManager();
$book = $entityManager->getRepository(Book::class)->find($id);
if (!$book) {
throw $this->createNotFoundException('No book found for id ' . $id);
}
$entityManager->remove($book);
$entityManager->flush();
return $this->redirectToRoute('list_books');
}
Rate this post
5 of 5 based on 3124 votesComments