How would you set the Cascade on removal? - symfony

I'm having some issues while deleting some objects, because those objects have other objects related to them.
For example. I've an entity named Home. This entity has some fields like name and description, aswel as id.
And then, I've an entity named Citizen which contains name, surname, home. This last field is directly related to Home.
So if I try to remove a HOME object, it crashes because there are some foreign key relating this object. What I'm doing at the moment, is searching for Citizens, and removing them, but this is not the best way to achieve this.
I know there's an annotation like "CASCADE" but I don't know where to place this annotation.
Where do I've to set this annotation to achieve what I'm trying to do?
Thanks.

In your home entity, you should have field, which contains all citizens.
/**
*
* #OneToMany(targetEntity="Citizen", mappedBy="home", cascade={"remove"})
*/
protected $citizens;

There are actually two ways of achieving your goal. You can use ORM level and Database level cascades.
ORM Level
// Home Entity
/**
* #comment The owning side has to use the inversedBy attribute of ManyToOne
*
* #ManyToOne(targetEntity="Citizen", inversedBy="home", cascade={"remove"})
*/
protected $citizens;
// ...
Database Level
// Home Entity
/**
* onDelete="CASCADE" is used on the joinColumn
* It will add On Delete Cascade to the foreign key column in the database.
*
* #ManyToOne(targetEntity="Citizen", inversedBy="home", cascade={"remove"})
* #ORM\JoinColumn(name="citizen_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $citizens;
// ...
Attention
You have to be careful where you set your cascade option.
You most likely don't want to have doctrine remove your owning side of the relation ( in this case delete the Home if you remove a citizen - therefore only set it on your Home entity ).
Alesh's example is wrong in your use case as mappedBy is always the inverse side of a relationship!
In your case Home will be the owning side as one Home will own multiple Citizens.
Now if you delete Home you want your Citizens to be homeless ( aka removed ).
Doctrine also only tracks the owning side of the relation for changes, now if you add a citizen to the collection ( for example with a collection form type ) with ...
$home->addCitizen($citizen);
... you likely want your citizen to be automatically persisted ( with cascade persist set ) when calling
$em->flush();

Related

Symfony 6 Doctrine relationship self-referencing uni-directional with linking table doesn't return data

Please let me assure you I could not find response anywhere, maybe there is one, but I was unable to locate it.
What I want to do is self-referencing relationship but with LINKING TABLE because I find them easier to read than self referencing foreign key. So I used the only example of this I found in Doctrine documentation
So here it is, this is class User which implements Userinterface too (Manager and Employee is just a USER with different roles)
/**
* Manager can have many employees
* #ORM\ManyToMany(targetEntity="User", mappedBy="managers")
*/
private $employees;
/**
* Employee can have many managers
* #ORM\ManyToMany(targetEntity="User", inversedBy="employees")
* #ORM\JoinTable(
* name="manager_employee",
* joinColumns={#ORM\JoinColumn(name="employeeId", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="managerId", referencedColumnName="id")}
* )
*/
private $managers;
Now the problem is - I am 99% positive I loaded my fixtures with Managers who have multiple employees and 99% positive I use getEmployees on a correct manager. I quinduple checked. Yet when I use this method I get empty collection. I dumped collection, I checked with Xdebug. Empty. Why? I have them in DB, db works flawlessly. There must be something wrong with this relationship part but its beyond me to think of any more reason.
I would be grateful for your help, I would not have asked if it was not my last resort. Thank you!

Many-to-many relations to itself with Symfony/Doctrine

I have a data model that contains persons and companies (amongst other things). I have created a many-to-many relation between them by creating an intermediate object PersonCompanyRelation that contains many-to-one relations to person and companies. The reason for this is that I want to store information about the relation. This works fine
Now I want to do the same but for linking persons to persons. I have again created a relationship object called PersonPersonRelation. The problem I run into is that in the Person object I have to specify what property the object is mapped to in the relationship object, however this is problematic since it will differ from relationship to relationship. Sometimes this will be A, sometimes it will be B. It doesn't matter which one it is but without a logical system I cannot logically retrieve the relations. How do I do this?
the code in PersonPersonRelation
/**
* #ORM\ManyToOne(targetEntity="Person", inversedBy="personPersonRelations")
*/
protected $personA;
/**
* #ORM\ManyToOne(targetEntity="Person", inversedBy="personPersonRelations")
*/
protected $personB;
the code in Person. Note how I need to specify the property in the relation it is mapped to, but from the perspective of Person I do not know whether this will be PersonA or PersonB
/**
* #ORM\OneToMany(targetEntity="PersonPersonRelation", mappedBy="personA")
*/
protected $personPersonRelations;
To clarify as asked below; The case is that I want to store professional relations between people, including details about that relation like how they met (colleagues, friends, family etc) as well as dates etc.
I'm sure that if you specify less generic names, all should be more clear.
Just to make and example, let's say that Person-Person relationship is a relation between Boss and Employee.
So, basically, every person will have two attributes
class Person
{
//other properties
/**
* #ORM\OneToMany(targetEntity="person", mappedBy="employees")
*/
$boss;
/**
* #ORM\ManyToOne(targetEntity="person", inversedBy="boss")
*/
$employees;
}
If I understood correctly the question, in every moment, you can alternatively try to retrieve:
from a boss-person point of view, all employees under him
from a employee-person point of view, its boss
Of course mine is only an example, don't know if you could fit your mind in it to adapt to your specific case. Hope so.

In Symfony2/ Doctrine: Setting foreign key to not null seems impossible in one to one relationship

In my picture entity I have an image attribute. (The other attributes are about alt, style etc. ). I noticed that attribute was not set as nullable= false. I decided to change that and after doing a doctrine schema update I noticed the column image_id is still set as nullable.
This led me to rethink my design and to set the Picture entity as extending from Image entity instead. I will try it next. I usually avoid class inheritance with my file related entities in Doctrine because it tend to cause too many problems.
However I would like to know. Is it expected behaviour from doctrine? SO far my One to One relationships have all been set to nullable. Is it impossible to make them not nullable? It would make sense since two closely related entities may be better off to be made one entity. However I would think this kind of concern should be left up to the developer's choice. As in my case, as I am reluctant to use inheritance on image entity.
the official documentation is not really explicit even though all examples show nullable foreign keys.
Here's the code:
/**
* #var
*
* #ORM\OneToOne(targetEntity="AnyRoutes\SiteBundle\Entity\Image", cascade={"persist", "remove"})
* ##ORM\JoinColumn(name="image_id", referencedColumnName="id", nullable=false)
*/
private $image;
##ORM\JoinColumn(name="image_id", referencedColumnName="id", nullable=false)
check if removing redundant # in ##ORM\ will help

Symfony2 and Doctrine - ManyToOne

I am trying to understand Symfony2, but there is something that is not making sense to me. I reversed engineered an existing database to produce my entities, so maybe thats the problem.
I have a table called availability_alert, nothing special, a few fields including an id (which is the primary key). This table has no link to anything else.
I then have a second table called booking_class, once again nothing special, but it does have the field $availabilityAlert which links to the availability_alerts tables id.
In essence, an Availability Alert can have one or many Booking Class.
Now in my booking class entity, I have the link
/**
* #var \AlertBundle\Entity\AvailabilityAlert
*
* #ORM\ManyToOne(targetEntity="AlertBundle\Entity\AvailabilityAlert")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="availability_alert_id", referencedColumnName="id")
* })
*/
private $availabilityAlert;
So this all looks ok. The setter for it though came out like so
public function setAvailabilityAlert(\AlertBundle\Entity\AvailabilityAlert $availabilityAlert = null)
{
$this->availabilityAlert = $availabilityAlert;
return $this;
}
So that appears to take an AvailabilityAlert Object as a parameter, not the AvailabilityAlert id?
So with the above, I am presuming doing something like this in my controller will not work?
$alert = new AvailabilityAlert();
$bookingClass = new BookingClass();
$bookingClass->setAvailabilityAlert($alert->getId());
Could someone give me some advice on whether things are correct here, or if I should be doing something else? Essentially AvailabilityAlert should be a static table, other tables link to this.
Any advice appreciated.
Thanks
Yes this is correct.
In the Doctrine world, you are working with objects, not with integers or strings, when it comes to relationships between Entities.
You can read more about Doctrine 2 relationships here: http://symfony.com/doc/current/book/doctrine.html#entity-relationships-associations
That's correct. You don't use integers, strings. It's because the relationships are given in entity annotations and Doctrine uses them to figure out what is used exactly to reference the one object from the other. This even let you change how objects reference themselves - for example you change the id to a compound primary key in AvailabilityAlert class and your code wouldn't change much except for the annotations.

Symfony2 - how to construct id = product mapping

I want to do mapping that does this:
User can own multiple Games. Games can have multiple owners.
I have id column in game table and game and user columns in ownership table. How I can connect these fields? I want to have game and user fields in ownership related to user and game tables.
I tried OneToMany and ManyToMany, but the first one results in generating additional columns. I don't want to insert anything in game table.
--edit--
My #ManyToMany code:
/**
* #ORM\ManyToMany(targetEntity="Ownership")
* #ORM\JoinTable(name="ownership",
* joinColumns={JoinColumn(name="user", referencedColumnName="id")},
* inverseJoinColumns={JoinColumn(name="game", referencedColumnName="id")}
* )
*/
It causes an error in Symfony's command line:
[Doctrine\Common\Annotations\AnnotationException]
[Semantical Error] Couldn't find constant JoinColumn, property GameShelf\Us
ersBundle\Entity\User::$ownership.
Of course you need many to many relations if, like you said:
User can own multiple Games. Games can have multiple owners.
The Doctrine should create third table (which could contains only two foreign keys: game_id and ownership_id).
The error is caused because Doctrine dosen't know what JoinColumn is. You just did wrong annotation because you forgot (again! ;)) precede JoinColumn with `#ORM. The right annotation should look like this:
/**
* #ORM\ManyToMany(targetEntity="Ownership")
* #ORM\JoinTable(name="ownership",
* joinColumns={#ORM\JoinColumn(name="user", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="game", referencedColumnName="id")}
* )
*/
Sounds like you need to introduce a new entity (something like OwnedGame) that holds the connection between a Game and an Owner (and possibly its own properties like when it was bought and such).
Then OwnedGame would be ManyToOne with Game and with Owner, and neither Game nor Owner would need to include a new column.
Your description of what you want doesn't fit at all.
On the one hand you want to have a relation between only Users and Games, and only between Games and Owners.
But on the other hand you say that Users and Owners are related in some way, but Games and Users aren't.
You should read through
http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html#many-to-many-unidirectional
and try to find what you really need.
I would recommend a ManyToMany relation with a join table. Thus you don't have to deal with additional fields in your tables

Resources