Doctrine ManyToMany with as specific field value - symfony

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

Related

Doctrine : Fetch "EAGER" and "Hydrate Array"

With Doctrine, I have fetch=EAGER in my entity :
class TrainingOrganization
{
/**
* #var TrainingOrganizationVersion[]|ArrayCollection
*
* #ORM\OneToMany(
* targetEntity="AppBundle\Entity\TrainingOrganizationVersion",
* mappedBy="trainingOrganization",
* cascade={"persist"},
* fetch="EAGER"
* )
* #ORM\OrderBy({"id" = "ASC"})
* #Assert\Valid()
* #Versionable
*/
private $versions;
Why when i do "hydrate array" it does not work ?
Screen of my dump for same entity (Second is "Hydrate array") :
With Hydration mode Query::HYDRATE_ARRAY, Doctrine will only return information about that 'row'. Since your versions attribute is not a field but a collection, it won't be returned.
If you want to have Collections included, use Objects instead (like your first screenshot).
If you really need your entities serialized (returning a multidimensional array instead of objects), use a serializer. Since you're using Symfony, you can easily use Symfony's Serializer Component. The JMSSerializerBundle is a popular alternative.

Doctrine2 cascade default value

I'm actually learning Symfony3 and more precisely the Doctrine2 relation between objects and I was wondering if there is a default value for the cascade parameter when you don't explicite it.
I seen in tutorials when it's necessary to use the remove value that the parameter is not specified, but there is no explanation about this fact.
So I mean is this
/**
* #ORM\ManyToOne(targetEntity="UTM\ForumBundle\Entity\UtmWebsiteTopics")
* #ORM\JoinColumn(nullable=false)
*/
private $topic;
equivalent to that ?
/**
* #ORM\ManyToOne(targetEntity="UTM\ForumBundle\Entity\UtmWebsiteTopics", cascade={"remove"})
* #ORM\JoinColumn(nullable=false)
*/
private $topic;
Thank you for reading and I hope you'll be able to bring me an answer. :D
In short, those two snippets are not the same. If you were to want to delete a specific entity that has relations to others through FK, you would need to explicitly remove() the related entities to avoid Integrity Constraint Violations.
Examples of each
Not defining cascade={"remove"}
public function removeEntityAction($id)
{
// Get entity manager etc....
$myEntity = $em->getRepository("MyEntity")->findBy(["id" => $id]);
foreach($myEntity->getTopics() as $topic) {
$em->remove($topic);
}
$em->remove($myEntity);
}
Defining cascade={"remove"}
public function removeEntityAction($id)
{
// Get entity manager etc....
$myEntity = $em->getRepository("MyEntity")->findBy(["id" => $id]);
$em->remove($myEntity);
}
Doctrine Cascade Operations
Doctrine - Removing Entities

Symfony entities without relational

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;
}

Doctrine2 deletes entity when removing ManyToOne Relation

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.

Composite key and form

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Ă !

Resources