In my setup I have a simple OneToMany relation without cascading or orphan removal.
class Position {
/**
* #var \Vorgaenge\Basis\DBBundle\Entity\Vorgang
*
* #ORM\ManyToOne(targetEntity="\Vorgaenge\Basis\DBBundle\Entity\Vorgang", inversedBy="Positionen")
* #ORM\JoinColumn(name="VID", referencedColumnName="VID")
*/
protected $Vorgang;
}
class Vorgang {
/**
* #var \Vorgaenge\Basis\DBBundle\Entity\Position
*
* #ORM\OneToMany(targetEntity="\Vorgaenge\Basis\DBBundle\Entity\Position", mappedBy="Vorgang")
* #ORM\OrderBy({"PID" = "ASC"})
*/
protected $Positionen;
}
All I do in my unittest is creating related entities ....
$entity = new \Vorgaenge\Basis\DBBundle\Entity\Vorgang();
$pos = new \Vorgaenge\Basis\DBBundle\Entity\Position();
$pos->Vorgang = $entity;
$pos2 = new \Vorgaenge\Basis\DBBundle\Entity\Position();
$pos2->Vorgang = $entity;
$em->persist($entity);
$em->persist($pos);
$em->persist($pos2);
$em->flush($entity);
.... and removing one of the relations after all entities an relations have been saved.
$pos->Vorgang = NULL;
$em->flush();
But somehow Doctrine deletes the entire entity $pos instead of only removing the relation by setting VID to 0.
I checked Doctrine's UnitOfWork doRemove and scheduleForDelete methods, but none of them seems to be involved.
Can anyone help me to understand why the Position entity is deleted and what needs to be done to prevent this?
Try to persist the object that you want keep like this:
$pos->Vorgang = NULL;
$em->persist($pos2);
$em->flush();
Problem solved. The view which showed the DB results after the script was inadequate. It now works as expected. The position is there.
Related
I'm trying to create a relation ManyToMany with doctrine (in symfony) that is depending on a field value.
/**
* #ORM\ManyToMany(targetEntity="Label")
* #ORM\JoinTable(
* name="Item_Label",
* joinColumns={#ORM\JoinColumn(name="item_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="label_id", referencedColumnName="id")}
* )
*/
private $labels;
Here we understand that we have to get data from Label via the table Item_label
We are on table Wine
Wine.id <-> Item_Label.item_id
<<< `WHERE Item_Label.item_type = 'wine'` >>>
`Item_Label.label_id` <-> `Label.id`
So, how can i write the WHERE Item_Label.item_type = 'wine' in annotations ?
Or a SqlFilter (I tried but failed) ?
Thanks for your help =)
So, it seems from this SO answer that it's not possible in doctrine.
My workaround was to add a method to my entity class as follows
public function foo($itemLabelRepo)
{
$found = $itemLabelRepo->findBy(['item_type'=>'wine', 'label_id'=>$this->getId()]);
if(count($found)!=1) {
throw new \Exception("Found non-one object from entity role");
}
return $found[0];
}
where $itemLabelRepo would be the repository to "Item_Label" in your case
I work with Symfony2 and Doctrine and I have a question regarding entities.
In a performance worries, I'm wondering if it is possible to use an entity without going all the associations?
Currently, I have not found another way to create a model inheriting the class with associations and associations specify NULL in the class that inherits.
thank you in advance
OK, a little detail, it's for a API REST (JSON).
This is my class :
/**
* Offerequipment
*
* #ORM\Table(name="offer_equipment")
* #ORM\Entity(repositoryClass="Charlotte\OfferBundle\Repository\Offerequipment")
*/
class Offerequipment
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Charlotte\OfferBundle\Entity\Offer")
* #ORM\JoinColumn(name="offer_id", referencedColumnName="id")
*/
private $offer;
/**
* #ORM\ManyToOne(targetEntity="Charlotte\ProductBundle\Entity\Equipment")
* #ORM\JoinColumn(name="equipment_id", referencedColumnName="id")
*/
private $equipment;
/**
* #VirtualProperty
*
* #return String
*/
public function getExample()
{
return $something;
}
and with QueryBuilder method, i can't get my virtual properties or getters.
Thanks for your help :)
Look at Serialization.
By serialising your entities, you can choose to exclude or expose a property of an entity when you render it.
Look at the Symfony built-in Serializer and/or JMSSerializer.
Otherwise, you can use QueryBuilder and DQL to choose what fields you want to fetch in your queries.
Like this, you can make your own find method in the Repository of your entities.
// src/AcmeBundle/Repository/FooRepository
class FooRepository extends \Doctrine\ORM\EntityRepository
// ...
public function find($id) {
$queryBuilder = $this->createQueryBuilder('e')
->select('e.fieldA', 'e.fieldB') // selected fields
->where('e.id = :id') // where statement on 'id'
->setParameter('id', $id);
$query = $queryBuilder->getQuery();
$result = $query->getResult();
}
// ...
}
Don't forget define the Repository in the corresponding Entity.
/**
* Foo.
*
* #ORM\Entity(repositoryClass="AcmeBundle\Repository\FooRepository")
*/
class Foo
{
// ...
}
By default Doctrine will not automatically fetch all of the associations in your entities unless you specifically each association as EAGER or unless you are using a OneToOne association. So if you are looking to eliminate JOINs, you can just use Doctrine in its default state and it won't JOIN anything automatically.
However, you this will not alleviate all of your performance concerns. Say, for example, you are displaying a list of 50 products in your application on a single page and you want to show their possible discounts, where discounts are an association on your product entity. Doctrine will create 50 additional queries just to retrieve the discount data unless you explicitly join the discount entity in your query.
Essentially, the Symfony profiler will be your friend and show you when you should be joining entities on your query - don't just think that because you aren't joining associations automatically that your performance will always be better.
Finally, after many days, I've found the solution to select only one entity.
VirtualProperties are found :)
public function findAllByOffer($parameters)
{
$queryBuilder = $this->createQueryBuilder('oe');
$queryBuilder->select('oe, equipment');
$queryBuilder->join('oe.equipment', 'equipment');
$result = $queryBuilder->getQuery()->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true)->getResult();
return $result;
}
Suppose we have a field with ManyToMany relation as
/**
* #var ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Users")
* #ORM\JoinTable(name="users_roles",
* joinColumns={#ORM\JoinColumn(name="User_Id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="Role_Id", referencedColumnName="id")})
*/
protected $userRole;
To remove one related element from table we can have this function in our entity:
/**
* Remove userRole
* #param \Acme\MyBundle\Entity\Users $user
*/
public function remvoveUserRole(\Acme\MyBundle\Entity\Users $user)
{
$this->userRole->removeElement($user);
}
The Question:
The ArrayCollection type has the function removeElement which is used to remove one element of the relationship. There is another function clear which in api says Clears the collection, removing all elements, therefore can I have a function like below in my entity to clear all the related elements so that by flushing it removes all?
/**
* Remove all user Roles
*/
public function remvoveAllUserRole()
{
$this->userRole->clear();
}
will it work for just ManyToMany related tables or it might work for ManyToOne, too?
Ţîgan Ion is right - removeElement/clear only removes those elements from memory.
However, I think you could achieve something as close depending on how did you configure cascade and orphanRemoval in your relationship.
$em = ...; // your EntityManager
$roles = $user->getRoles();
$roles->clear();
$user = $em->merge($user); // this is crucial
$em->flush();
In order for this to work, you need to configure User relationship to
cascade={"merge"} - this will make $em->merge() call propagate to roles.
orphanRemoval = true - since this is #ManyToMany, this will make EntityManager remove free-dangling roles.
Can't test this now, but as far as I can see it could work. I will try this out tomorrow and update the answer in need be.
Hope this helps...
Note: This logic works for ManyToMany relationship, but not for ManyToOne
I tested the way to delete all related roles for specific use (ManyToMany) and it worked. What you need is to define a function in your UserEntity as
/**
* Remove all user Roles
*/
public function remvoveAllUserRole()
{
$this->userRole->clear();
}
Then in your controller or anywhere else(if you need) you can call the function as below
$specificUser = $em->getRepository('MyBundle:Users')->findOneBy(array('username' => 'test user'));
if (!empty($specificUser)) {
$specificUser->removeAllUserRole();
$em->flush();
}
Then it will delete all related roles for the test user and we don't need to use the for loop and remove them one by one
if I'm not mistaken, this will not work, you have to delete the "role
s" from the arrayCollection directly from the database
$roles = $user->getRoles()
foreach $role from $roles
$em->remove($role);
$em->flush();
now you should get an empty collection
p.s: the best way is to test your ideas
I have the following associations in my database (simplified version):
This is a Many-To-Many association but with an attribute on the joining table, so I have to use One-To-Many/Many-To-One associations.
I have a form where I can add as many relations as I want to one order item and create it at the same time (mainly inspired by the How to Embed a Collection of Forms tutorial from the documentation.
When I post the form, I get the following error:
Entity of type TEST\MyBundle\Entity\Relation has identity through
a foreign entity TEST\MyBundle\Entity\Order, however this entity
has no identity itself. You have to call EntityManager#persist() on
the related entity and make sure that an identifier was generated
before trying to persist 'TEST\MyBundle\Entity\Relation'. In case
of Post Insert ID Generation (such as MySQL Auto-Increment or
PostgreSQL SERIAL) this means you have to call EntityManager#flush()
between both persist operations.
I understand this error because Doctrine tries to persist the Relation object(s) related to the order since I have the cascade={"persist"} option on the OneToMany relation. But how can I avoid this behavior?
I have tried to remove cascade={"persist"} and manually persist the entity, but I get the same error (because I need to flush() order to get the ID and when I do so, I have the same error message).
I also tried to detach() the Relation objects before the flush() but with no luck.
This problem seems unique if 1) you are using a join table with composite keys, 2) forms component, and 3) the join table is an entity that is being built by the form component's 'collection' field. I saw a lot of people having problems but not a lot of solutions, so I thought I'd share mine.
I wanted to keep my composite primary key, as I wanted to ensure that only one instance of the two foreign keys would persist in the database. Using
this entity setup as an example
/** #Entity */
class Order
{
/** #OneToMany(targetEntity="OrderItem", mappedBy="order") */
private $items;
public function __construct(Customer $customer)
{
$this->items = new Doctrine\Common\Collections\ArrayCollection();
}
}
/** #Entity */
class Product
{
/** #OneToMany(targetEntity="OrderItem", mappedBy="product") */
private $orders;
.....
public function __construct(Customer $customer)
{
$this->orders = new Doctrine\Common\Collections\ArrayCollection();
}
}
/** #Entity */
class OrderItem
{
/** #Id #ManyToOne(targetEntity="Order") */
private $order;
/** #Id #ManyToOne(targetEntity="Product") */
private $product;
/** #Column(type="integer") */
private $amount = 1;
}
The problem I was facing, if I were building an Order object in a form, that had a collection field of OrderItems, I wouldn't be able to save OrderItem entity without having saved the Order Entity first (as doctrine/SQL needs the order id for the composite key), but the Doctrine EntityManager wasn't allowing me to save the Order object that has OrderItem attributes (because it insists on saving them en mass together). You can't turn off cascade as it will complain that you haven't saved the associated entities first, and you cant save the associated entities before saving Order. What a conundrum. My solution was to remove the associated entities, save Order and then reintroduce the associated entities to the Order object and save it again. So first I created a mass assignment function of the ArrayCollection attribute $items
class Order
{
.....
public function setItemsArray(Doctrine\Common\Collections\ArrayCollection $itemsArray = null){
if(null){
$this->items->clear();
}else{
$this->items = $itemsArray;
}
....
}
And then in my Controller where I process the form for Order.
//get entity manager
$em = $this->getDoctrine()->getManager();
//get order information (with items)
$order = $form->getData();
//pull out items array from order
$items = $order->getItems();
//clear the items from the order
$order->setItemsArray(null);
//persist and flush the Order object
$em->persist($order);
$em->flush();
//reintroduce the order items to the order object
$order->setItemsArray($items);
//persist and flush the Order object again ):
$em->persist($order);
$em->flush();
It sucks that you have to persist and flush twice (see more here Persist object with two foreign identities in doctrine). But that is doctrine for you, with all of it's power, it sure can put you in a bind. But thankfully you will only have to do this when creating a new object, not editing, because the object is already in the database.
You need to persist and flush the original before you can persist and flush the relationship records. You are 100% correct in the reason for the error.
I assume from the diagram that you are trying to add and order and the relation to the contact at the same time? If so you need to persist and flush the order before you can persist and flush the relationship. Or you can add a primary key to the Relation table.
I ended up creating a separated primary key on my Relation table (instead of having the composite one).
It looks like it is a dirty fix, and I am sure there is a better way to handle this situation but it works for now.
Here is my Relations entity:
/**
* Relation
*
* #ORM\Entity
*/
class Relation
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Contact", inversedBy="relation")
*/
protected $contact;
/**
* #ORM\ManyToOne(targetEntity="Order", inversedBy="relation")
*/
protected $order;
/**
* #var integer
*
* #ORM\Column(name="invoice", type="integer", nullable=true)
*/
private $invoice;
//Rest of the entity...
I then added the cascade={"persist"} option on the OneToMany relation with Order:
/**
* Orders
*
* #ORM\Entity
*/
class Order
{
/**
* #ORM\OneToMany(targetEntity="Relation", mappedBy="order", cascade={"persist"})
*/
protected $relation;
//Rest of the entity...
Et voilà!
After reading the Doctrine reference and the Symfony tutorial on it, I started integrating it in a project. I'm experiencing a problem I thought doctrine could solve:
I want to have Libraries with many Collections, which I assume to be a 'ManytoOne' relationship as the Collection will keep the foreign key.
Some snippets:
In Library:
/**
*
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="Collection", mappedBy="library")
*/
private $collections;
In collection:
/**
* #var Library
*
* #ORM\ManyToOne(targetEntity="Library", inversedBy="collections")
* #ORM\JoinColumn(name="library_id", referencedColumnName="id")
*/
private $library;
Since most of this annotations are default and could be left out it's a pretty basic setup.
A sample controller code:
$library = new Library();
$library->setName("Holiday");
$library->setDescription("Our holiday photos");
$collection = new Collection();
$collection->setName("Spain 2011");
$collection->setDescription("Peniscola");
$library->addCollection($collection);
$em=$this->getDoctrine()->getManager();
$em->persist($collection);
$em->persist($library);
$em->flush();
The code above won't set the library_id column in the Collection table, which I assume is because Library is not the owner.
$library = new Library();
$library->setName("Holiday");
$library->setDescription("Our holiday photos");
$collection = new Collection();
$collection->setName("Spain 2011");
$collection->setDescription("Peniscola");
$collection->setLibrary($library); <--- DIFFERENCE HERE
$em = $this->getDoctrine()->getManager();
$em->persist($collection);
$em->persist($library);
$em->flush();
Works. But I want to be able to use the library add and remove methods.
Is it common to alter these add and remove methods to call the setLibrary method?
public function addCollection(\MediaBox\AppBundle\Entity\Collection $collections)
{
$this->collections[] = $collections;
$collections->setLibrary($this);
return $this;
}
and
public function removeCollection(\MediaBox\AppBundle\Entity\Collection $collections)
{
$this->collections->removeElement($collections);
$collections->setLibrary(null);
}
I don't think that's very nice.
Is it best practice in doctrine or ORM in general?
Kind regards and thanks in advance!
Obviously this is the way to go.
For the case someone needs it:
http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/working-with-associations.html#association-management-methods
Explains this problem.