Symfony extends entity - symfony

its posible to extend entity group by other entity gtoup also changin OneToOne/OneToMany relations.
For example i tried to exted UserTemp by User but on schema validation i receive error of mapping invalid.
class User
/**
* #ORM\Table(name="d1_user")
* #ORM\Entity(repositoryClass="App\Repository\UserRepository")
*/
class User
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string|null
*
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $name;
/**
* #var UserAddress
*
* #ORM\OneToMany(targetEntity="UserAdress", mappedBy="user", cascade={"persist", "remove"}, orphanRemoval=true)
*/
private $address;
}
class UserTemp
/**
* #ORM\Table(name="d1_user")
* #ORM\Entity(repositoryClass="App\Repository\UserTempRepository")
*/
class UserTemp extends User
{
/**
* #var UserTempAddress
*
* #ORM\OneToMany(targetEntity="UserTempAdress", mappedBy="user", cascade={"persist", "remove"}, orphanRemoval=true)
*/
private $address;
}

You try
/**
* #EntityExtension("User") //path Class User
*/
trait UserTempTrait
{
/**
* #var UserTempAddress
*
* #ORM\OneToMany(targetEntity="UserTempAdress", mappedBy="user", cascade={"persist", "remove"}, orphanRemoval=true)
*/
private $address;
}

Related

how to add a foreign key (one to many) in symfony

i have two entities 'Panier' and 'Reservation' i want to add a one to many foreign key (the Entity 'Panier' can have many 'Reservation' and 'Reservation' has only one 'Panier' id ) , so i have to add a foreign key 'id' of 'Panier' in my Reservation entity class .
this is my Reservation class :
class Reservation
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="dateReservation", type="datetime", nullable=false)
*/
private $datereservation = 'CURRENT_TIMESTAMP';
/**
* #var integer
*
* #ORM\Column(name="quantite", type="integer", nullable=false)
*/
private $quantite;
/**
* #var float
*
* #ORM\Column(name="total", type="float", precision=10, scale=0, nullable=true)
*/
private $total;
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=255, nullable=false)
*/
private $type;
/**
* #var string
*
* #ORM\Column(name="seat", type="string", length=255, nullable=false)
*/
private $seat;
/**
* #var integer
*
* #ORM\Column(name="payer", type="integer", nullable=true)
*/
private $payer;
/**
* #var string
*
* #ORM\Column(name="nomReservation", type="string", length=255, nullable=true)
*/
private $nomreservation;
/**
* #var \Event
*
* #ORM\ManyToOne(targetEntity="Event")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="event_id", referencedColumnName="id")
* })
*/
private $event;
/**
* #var \User
*
* #ORM\ManyToOne(targetEntity="User")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* })
*/
private $user;
<?php
/** #Entity */
class Reservation {
/**
* #ManyToOne(targetEntity="Panier", inversedBy="reservations")
* #JoinColumn(name="panier_id", referencedColumnName="id")
*/
private $panier;
}
/** #Entity */
class Panier {
/**
* One Panier has many Reservations. This is the inverse side.
* #OneToMany(targetEntity="Reservation", mappedBy="panier")
*/
private $reservations;
public function __construct() {
$this->features = new ArrayCollection();
}
}

Doctrine request crash with composite key

I'm facing a big problem with Doctrine when i'm requesting a table with a composite primary key referencing foreign keys.
I have a 3 entities:
Library(idLibrary,adress), Book(idBook,title,pageCount), Container(idLibrary,idBook, quantity).
Everything is generated without any errors but when i'm doing findAll() request on my Container repository my browser freezes and nothing is showed like it was stuck in a loop (there 3 rows in my Container table).
class Bibliotheque
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="name", type="string", length=60)
*/
private $name;
/**
* #ORM\Column(name="adress", type="string", length=60)
*/
private $adress;
}
class Conteneur
{
/**
* Many Containers have One library.
* #ORM\Id
* #ORM\OneToOne(targetEntity="Bibliotheque")
* #ORM\JoinColumn(name="libraryId", referencedColumnName="id")
*/
private $library;
/**
* One Container has One book.
* #ORM\Id
* #ORM\OneToOne(targetEntity="Livre")
* #ORM\JoinColumn(name="bookId", referencedColumnName="id")
*/
private $book;
/**
* #ORM\Column(name="quantity", type="integer")
*/
private $quantity;
}
class Livre
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #ORM\Column(name="pageCount", type="integer")
*/
private $pageCount;
/**
* Un livre a plusieurs auteurs
* #ORM\ManyToMany(targetEntity="Auteur")
* #ORM\JoinTable(name="books_authors",
* joinColumns={#ORM\JoinColumn(name="book_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="author_id", referencedColumnName="id")}
* )
*/
private $authors;
}
class Auteur
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="name", type="string", length=60)
*/
private $name;
/**
* #ORM\Column(name="surname", type="string", length=60)
*/
private $prenom;
/**
* #ORM\Column(name="birthDate", type="date")
*/
private $birthDate;
}
firstly, please use only French or English for class name and variable.
Add id inside class "Container" and remove annotation #ORM\id for attributes "library" and "book"
Define attribute "authors" with ArrayCollection and add method getAuthors(), addAuthor(Author $author), removeAuthor(Author $author)
And rename the tables name => "name_id" not "nameId"
look documention http://symfony.com/doc/current/doctrine.html
class Library
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=60)
*/
private $name;
/**
* #var string $address
*
* #ORM\Column(name="address", type="string", length=60)
*/
private $address;
}
class Container
{
/**
* #var integer $id
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* Many Containers have One library.
*
* #ORM\OneToOne(targetEntity="Library")
* #ORM\JoinColumn(name="library_id", referencedColumnName="id")
*/
private $library;
/**
* One Container has One book.
*
* #ORM\OneToOne(targetEntity="Book")
* #ORM\JoinColumn(name="book_id", referencedColumnName="id")
*/
private $book;
/**
* #ORM\Column(name="quantity", type="integer")
*/
private $quantity;
}
class Book
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $title
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string $pageCount
*
* #ORM\Column(name="page_count", type="integer")
*/
private $pageCount;
/**
* A book have many authors
*
* #var ArrayCollection $authors
*
* #ORM\ManyToMany(targetEntity="Auteur")
* #ORM\JoinTable(name="books_authors",
* joinColumns={#ORM\JoinColumn(name="book_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="author_id", referencedColumnName="id")}
* )
*/
private $authors;
/**
* #return ArrayCollection
*/
public function getAuthors()
{
return $this->authors;
}
/**
* #param Author $author
*
* #return $this
*/
public function addAuthor(Author $author)
{
$this->authors->add($author);
return $this;
}
/**
* #param Author $author
*
* #return $this
*/
public function removeAuthor(Author $author)
{
$this->authors->removeElement($author);
return $this;
}
}
class Author
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $firstname
*
* #ORM\Column(name="firstname", type="string", length=60)
*/
private $firstname;
/**
* #var string $lastname
*
* #ORM\Column(name="lastname", type="string", length=60)
*/
private $lastname;
/**
* #var DateTime $birthDate
*
* #ORM\Column(name="birthDate", type="date")
*/
private $birthDate;
}

Symfony save date for every change status

how i can to do this: I have OrderWork entity this for order and have relation manyToMany with Status entity. All work good, but i want have date for every saved and updated order.
* Order
*
* #ORM\Table(name="order_work")
* #ORM\Entity(repositoryClass="AppBundle\Repository\OrderWorkRepository")
*/
class OrderWork
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Client", cascade={"persist"})
* #ORM\JoinColumn(name="client_id", referencedColumnName="id")
*/
private $client;
/**
* #var string
*
* #ORM\Column(name="orderNumber", type="string", length=255)
*/
private $orderNumber;
/**
* #var string
*
* #ORM\Column(name="orderCity", type="string", length=255)
*/
private $orderCity;
/**
* #var date
*
* #ORM\Column(name="date", type="string", length=255)
*/
private $date;
/**
* #var \DateTime
*
* #ORM\Column(name="orderDate", type="string", length=255, options={"default": NULL})
*/
private $orderDate;
/**
* #var \DateTime
*
* #ORM\Column(name="returnDate", type="string", length=255, nullable=true)
*/
private $returnDate;
/**
* #var string
*
* #ORM\Column(name="device", type="string", length=255)
*/
private $device;
/**
* #ORM\ManyToOne(targetEntity="SurrogatePhone", cascade={"persist"})
* #ORM\JoinColumn(name="surrogate_id", referencedColumnName="id")
*/
private $surrogatePhone;
/**
* #var int
*
* #ORM\Column(name="orderType", type="integer")
*/
public $orderType;
/**
* #ORM\ManyToMany(targetEntity="Status")
* #ORM\JoinTable(name="order_status",
* joinColumns={#ORM\JoinColumn(name="order_id", referencedColumnName="id", unique=false)},
* inverseJoinColumns={#ORM\JoinColumn(name="status_id", referencedColumnName="id", unique=false)}
* )
*/
private $status;
How better resolve this solution?
Define date in your constructor (for creating):
class OrderWork
{
//...
public function __construct()
{
$this->date = new DateTime();
}
}
And update date field when updating:
$orderWork->setDate(new DateTime());
$em->flush();

Entity inheritance in Doctrine doesn't include OneToOne-relationships

Trying to utilize inheritance, I've created the following entities:
/**
* #ORM\Table(name="persons")
* #ORM\Entity()
*/
class Person
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
protected $name;
/**
* #ORM\OneToOne(targetEntity="Image", cascade={"persist"})
* #ORM\JoinColumn(name="image_id", referencedColumnName="id")
*/
protected $image;
}
/**
* #ORM\Table(name="actors")
* #ORM\Entity()
*/
class Actor extends Person
{
/**
* #ORM\Column(name="character", type="string", length=255)
*/
private $character;
}
/**
* #ORM\Table(name="images")
* #ORM\Entity()
*/
class Image
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="path", type="string", length=255)
*/
private $path;
}
Which almost works perfectly. The generated actors-table contains all the persons-fields, except for the image-relation. I've tried to change the relation to a ManyToOne, which didn't help.
How to make the Actor-entity also inherit all joined fields? I'm open to other solutions, if the above isn't ideal.
You need a parent construct in your Actor class:
public function __construct()
{
parent::__construct();
// your own logic
}
It is advised that you add an ID aswell.

Doctrine2 cascade remove with multiple parents

I have a series of classes with a slightly complicated set of references between the properties of those classes. I am trying to remove an entity and have that remove be cascaded to its children, but I'm running into foreign key constraint errors. Here is an example of my class structure:
<?php
/**
* #ORM\Entity
* #ORM\Table(name="student_tests")
*/
class StudentTest implements IEntityAccess {
/**
*
* #var int
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var StudentTestItem[]
* #ORM\OneToMany(targetEntity="StudentTestItem", mappedBy="studentTest", cascade{"remove","persist"})
*/
protected $studentTestItems;
/**
* #var Test
* #ORM\ManyToOne(targetEntity="Test", inversedBy="studentTests")
*/
protected $test;
/**
* #var \DateTime
* #ORM\Column(type="datetime", nullable=true)
*/
protected $created;
/**
* #var User
* #ORM\ManyToOne(targetEntity="User", inversedBy="studentTests")
*/
protected $student;
}
//...
<?php
/**
* #ORM\Entity
* #ORM\Table(name="student_test_items")
*/
class StudentTestItem {
/**
*
* #var int
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var StudentTest
* #ORM\ManyToOne(targetEntity="StudentTest", inversedBy="studentTestItems")
*/
protected $studentTest;
/**
* #var User
* #ORM\ManyToOne(targetEntity="User", inversedBy="studentTestItems", cascade={"persist"})
*/
protected $student;
/**
* #var TestItem
* #ORM\ManyToOne(targetEntity="TestItem", inversedBy="studentTestItems", cascade{"persist"})
*/
protected $testItem;
}
//...
/**
*
* #ORM\Table(name="tests")
* #ORM\Entity
*
* #ORM\HasLifecycleCallbacks
*/
class Test implements IEntityAccess {
/**
*
* #var int
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var \DateTime
* #ORM\Column(type="datetime", nullable=true)
*/
protected $startDate;
/**
* #var StudentTest[]
* #ORM\OneToMany(targetEntity="StudentTest", mappedBy="test" )
*/
protected $studentTests;
/**
* #var TestItem[]
* #ORM\OneToMany(targetEntity="TestItem", mappedBy="test", cascade={"all"})
*/
protected $items;
}
//...
/**
*
* #ORM\Table(name="test_items")
* #ORM\Entity
*/
abstract class TestItem {
/**
*
* #var int
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var Test
* #ORM\ManyToOne(targetEntity="Test", inversedBy="items")
*/
/**
* #var StudentTestItem[]
* #ORM\OneToMany(targetEntity="StudentTestItem", mappedBy="testItem")
*/
protected $studentTestItems;
}
/**
* This is the primary user object. Used for login and all the other
* good stuff.
*
* #ORM\Table(name="users")
* #ORM\HasLifecycleCallbacks
class User implements AdvancedUserInterface, \Serializable, IEntityAccess
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #var int
*/
private $id;
/**
* #var StudentTest[]
* #ORM\OneToMany(targetEntity="StudentTest", mappedBy="student", cascade={"persist", "remove"})
*/
protected $studentTests;
/**
* #var StudentTestItem[]
* #ORM\OneToMany(targetEntity="StudentTestItem", mappedBy="student", cascade={"persist", "remove"})
*/
protected $studentTestItems;
}
Let's say I want to delete a student test, and have that delete cascaded to its StudentTestItem children. To do so, I run the following code inside of a controller.
//... blah blah class definition
/**
* Delete a student test
*
* #return \Symfony\Component\HttpFoundation\Response
* #Route("/studenttest/delete", name="student_test_delete")
*/
public function DeleteStudentTestAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$studentTest = $em->getRepository("MyAcmeBundle:StudentTest")->findOneBy(array("id" => 3));
$em->remove($studentTest);
$em->flush();
return $this->redirect($this->generateUrl('student_delete_success'));
}
When I try to run that code, I get the following error message:
An exception occurred while executing 'DELETE FROM student_tests WHERE id = ?' with params [3]:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`my_acme_bundle/student_test_items`, CONSTRAINT `FK_71FA2A7F36BB1A1` FOREIGN KEY (`student_test_id`) REFERENCES `student_tests` (`id`))
500 Internal Server Error - DBALException
NOW, if I remove all references to studentTestItems from the classes, i.e. I comment out $studentTestItems from the TestItem and User classes, it deletes fine without that issue. Why is this happening? Does Doctrine keep track of the parent references through associations or something?
Looks like you forgot to add ON DELETE CASCADE to the foreign key constraint. Try changing the following association in class StudentTestItem:
/**
* #var StudentTest
* #ORM\ManyToOne(targetEntity="StudentTest", inversedBy="studentTestItems")
*/
protected $studentTest;
To this:
/**
* #var StudentTest
* #ORM\ManyToOne(targetEntity="StudentTest", inversedBy="studentTestItems")
* #ORM\JoinColumn(name="student_test_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $studentTest;

Resources