Doctrine Results Missing Entity - php

I've been trying to figure this out for a while now. Let's start with the basic information, I have a client table and a contact table. The client table has a OneToMany and OneToOne relation with contact
class Client
{
/**
* #var int
* #Id
* #Column(type="integer", nullable=false, unique=true, options={"comment":"Auto incrementing client_id of each client"})
* #GeneratedValue
*/
protected $pid;
/**
* #OneToMany(targetEntity="Contact", mappedBy="client")
* #JoinColumn(name="contact_id", referencedColumnName="pid")
* #var Contact[]
*/
protected $contact;
/**
* #OneToOne(targetEntity="Contact")
* #JoinColumn(name="defaultcontact_id", referencedColumnName="pid", nullable=true)
* #var Contact
*/
protected $default_contact;
The contact table has a ManyToOne relation with Client:
class Contact
{
/**
* #var int
* #Id
* #Column(type="integer", nullable=false, unique=true, options={"comment":"Auto incrementing user_id of each user"})
* #GeneratedValue
*/
protected $pid;
/**
* #ManyToOne(targetEntity="Client", inversedBy="contact")
* #JoinColumn(name="client_id", referencedColumnName="pid")
*/
protected $client;
Here's the query that I've been using:
$qb = $entityManager->createQueryBuilder();
$qb->select("cn as contact", "cl as client")
->from('DB\Contact', 'cn')
->innerJoin('cn.client', 'cl')
->where(
$qb->expr()->andX(
$qb->expr()->eq('cl.client_name', '?1'),
$qb->expr()->eq('cn.pid', '?2')
)
)
->setParameter(1, $client)
->setParameter(2, $contact);
try
{
$result = $qb->getQuery()->getOneOrNullResult();
}
I want both the contact and the client. And this is where I'm having problems: array_keys($result) ends up outputting:
Array
(
[0] => contact
)
I wanted something like this:
[0] => contact
[1] => client
In other words, the Client Entity is missing. Flipping the SELECT FROM from the Contact to the Client repository yielded the reverse situation, contact was missing.
I've checked over the previous code, while entityManager was reused from the login step, this is the first time the Client and Contact repository are accessed so I don't believe it's a caching problem.
Here's the SQL statement being executed:
Executing SQL:
SELECT c0_.pid AS pid0, c0_.caller AS caller1, c0_.address_1 AS address_12, c0_.address_2 AS address_23,
c0_.unit AS unit4, c0_.city AS city5, c0_.state AS state6, c0_.zip_code AS zip_code7, c0_.phone AS phone8,
c0_.email AS email9, c0_.is_active AS is_active10, c0_.date_created AS date_created11,
c0_.date_last_modified AS date_last_modified12, c1_.pid AS pid13, c1_.client_name AS client_name14,
c1_.is_active AS is_active15, c1_.date_created AS date_created16, c1_.date_last_modified AS date_last_modified17,
c0_.client_id AS client_id18, c0_.created_by_id AS created_by_id19, c0_.last_modified_by_id AS last_modified_by_id20,
c1_.defaultcontact_id AS defaultcontact_id21, c1_.created_by_id AS created_by_id22,
c1_.last_modified_by_id AS last_modified_by_id23
FROM contacts c0_
INNER JOIN clients c1_ ON c0_.client_id = c1_.pid
WHERE c1_.client_name= ? AND c0_.pid = ?
As a sidenote, if I alter the select so that the missing entity accesses a specific column, I'll get the desired values.
e.g.
$qb->select("cn as contact", "cl.pid as client")
->from('RGAServ\DB\Contact', 'cn')
will have the following array_keys($result):
Array
(
[0] => contact
[1] => client
)
So I can assure you that the client does exist in the database and it should be properly attached to the contact, it's just that under the first select statement where I want the whole entity and not just one column, the entity ends up not being pushed into the result array.
Why is this? Are there too many columns in the Sql statement? Am I forgetting something in the annotations?

First: You can't have different entities in the resulting array: every row in the result must be in the same format.
Second: If you examine your SQL query closely you'll notice that the one row that is returned contains both the contact (c0_) and the client (c1_).
Try executing the SQL query in the database to see the result.

After looking through a bunch of stack overflow questions, I've come to the following conclusion: It looks like this is how doctrine handles "Fetch Joins".
The big clue comes from here:
Doctrine Regular vs Fetch join
With supporting evidence for this behavior's existence coming from:
Doctrine - entities not being fetched
Doctrine join bypass lazy loading
Doctrine2 query with select on multiple entities from different Symfony2 bundles
More specifically, this quote from the doctrine documentation starts to make sense (http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html#joins):
When Doctrine hydrates a query with fetch-join it returns the class in
the FROM clause on the root level of the result array. In the previous
example an array of User instances is returned and the address of each
user is fetched and hydrated into the User#address variable. If you
access the address Doctrine does not need to lazy load the association
with another query.
In layman's terms, during a FETCH JOIN, contact (or client if I'm SELECTing FROM the client repository) is designated as the root entity. Whatever is found for Client will then be pushed into the contact's $client variable to be retrieved afterwards using a getter accessor.
The retrieval itself will not need a follow-up database query to fetch the client entity. I'll need to do a little testing, but it looks like this behavior was for the situation when multiple results are returned during the join. Instead of cluttering up the results, they're organized under an intuitive location.
In other words, I had the wrong expectations and was looking in the wrong spot. The client entity did indeed come back, but it wasn't placed in results. It was filed under contact. Retrieving it separately is, therefore, a given but at least it won't need another database call.
At least now, I believe I know why when I had Client in the from field, I was getting one specific contact instead of all of them when I tried to use the getContact() accessor.

Related

Doctrine prevent object deletion

In my project I have two entities: planifications and selections.
There is a relation between these two objects: A planification MUST contain ONE selection. The same selection can be used by multiple planifications.
The generated code looks like this:
// Planification.php - class Planification
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Selection", inversedBy="planifications")
* #ORM\JoinColumn(name="selection_id", referencedColumnName="id")
*/
private $selection;
// Selection.php - class Selection
/**
* #ORM\OneToMany(targetEntity="App\Entity\Planification", mappedBy="selection")
*/
private $planifications;
What I would like to do is not allow a selection to be deleted if it is referenced by a planification. In other words, if a planification contains a selection - that selection can not be deleted. What happens to me is if I try to delete a selection that is in a planification, the operation completes successfully, and the $selection member in the Planification class contains NULL.
Would fixing this be possible in doctrine? I have tried adding nullable=false (on the $selection member) and onDelete="NO ACTION", and both solutions don't work.
The correct Doctrine annotation to disallow Planification::$selection to be null, would be:
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Selection", inversedBy="planifications")
* #ORM\JoinColumn(name="selection_id", nullable=false)
*/
private $selection;
(You do not need the referencedColumnName setting, since it defaults to id, and nullable=false goes in the #JoinColumn annotation).
Having the annotation will not update the DB to fit this particular definition.
Execute bin/console doctrine:schema:update --dump-sql to see the needed SQL to update your table definition, and run the resultant appropriate SQL statements against your DB to update the DB schema.

How do I set up a Rails "has_one :through" association with Doctrine?

I come from a Rails background and am not really familiar with Doctrine. I am trying to set up a similar association to this one in Rails.
I have a UserRelation entity that contains a combination of user_id and company_id with a primary key. The same user can belong to multiple companies, and most data is stored with user_relation_id.
So, in this example I have a Template that has the following association set up which works fine:
/**
* The UserRelation entity who created the template.
*
* #ORM\ManyToOne(targetEntity="UserRelation")
* #ORM\JoinColumn(name="user_relation_id", referencedColumnName="id", nullable=false)
*/
protected $creator;
In this example I know I can just add a method to my template entity along the lines of:
public function getUser(): User
{
return $this->creator->getUser();
}
but I need it to be filterable so that I can get all Template entities by user_id or company_id in a repository or controller like this:
$company = $entityManager->getRepository('Company')->find($company_id);
$templatesForCompany = $entityManager->getRepository('Template')->findBy('company' => $company);
Is there any way to set up this relationship so I can query it like above, instead of having to resort to raw SQL?

Doctrine merging entity with unidirectional OneToMany not clearing database entries

First off, I use Doctrine v2.6.2 with Symfony v4.1.7.
I have an entity Product which (among others) has a unidirectional one-to-many relation with another entity AlternativeDuration. Following Doctrine's documentation, the mapping in my product class looks like this:
/**
* #ORM\ManyToMany(
* targetEntity="AlternativeDuration",
* cascade={"persist", "merge", "remove"},
* orphanRemoval=true
* )
* #ORM\JoinTable(name="ProductAlternativeDurations",
* joinColumns={#ORM\JoinColumn(name="product_id", referencedColumnName="id", onDelete="CASCADE", nullable=false)},
* inverseJoinColumns={#ORM\JoinColumn(name="alternative_duration_id", referencedColumnName="id", unique=true, onDelete="CASCADE", nullable=false)}
* )
*/
protected $alternativeDurations;
My application recently started using React, this means I now submit a JSON representation of my product (along with an array of alternative durations) which I need to deserialize into the Product entity in the back-end. I use the JMS serializer with default configuration for this.
Now the problem I'm having happens when editing an existing product, the product already has an alternative duration which I delete. The submitted JSON looks like this:
{
"id": 1, # the ID of the existing product here
"alternativeDurations": [] # empty array because the entry is removed
}
In the back-end I successfully deserialize the JSON string:
$serializedProduct = $this->serializer->deserialize($jsonString, Product::class, 'json');
I verified here that the $serializedProduct has no alternative durations. Then I follow with a merge + flush. I expect the merge to fetch the existing product and supplement it with the $serializedProduct.
$em->merge($serializedProduct); # $em being the EntityManager.
$em->flush();
Now I would expect the AlternativeDuration entry, along with the ProductAlternativeDurations join table entry being removed. The result, however, is that the entry in ProductAlternativeDurations is removed but the AlternativeDuration is still there.
I'm at a loss now, anyone can give some pointers on why the AlternativeDuration entry is not deleted?
EDIT 19-11-2018:
It seems this is a known bug in Doctrine: #2542
Also merge will be removed in Doctrine3 so I will probably need to rethink this approach in general.

Doctrine 2 - How to use objects retrieved from cache in relationships

I'm working in a project that use Doctrine 2 in Symfony 2 and I use MEMCACHE to store doctrine's results.
I have a problem with objects that are retrieved from MEMCACHE.
I found this post similar, but this approach not resolves my problem: Doctrine detaching, caching, and merging
This is the scenario
/**
* This is in entity ContestRegistry
* #var contest
*
* #ORM\ManyToOne(targetEntity="Contest", inversedBy="usersRegistered")
* #ORM\JoinColumn(name="contest_id", referencedColumnName="id", onDelete="CASCADE"))
*
*/
protected $contest;
and in other entity
/**
* #var usersRegistered
*
* #ORM\OneToMany(targetEntity="ContestRegistry", mappedBy="contest")
*
*/
protected $usersRegistered;
Now imagine that Contest is in cache and I want to save a ContestRegistry entry.
So I retrieve the object contest in cache as follows:
$contest = $cacheDriver->fetch($key);
$contest = $this->getEntityManager()->merge($contest);
return $contest;
And as last operation I do:
$contestRegistry = new ContestRegistry();
$contestRegistry->setContest($contest);
$this->entityManager->persist($contestRegistry);
$this->entityManager->flush();
My problem is that doctrine saves the new entity correctly, but also it makes an update on the entity Contest and it updates the column updated. The real problem is that it makes an update query for every entry, I just want to add a reference to the entity.
How I can make it possible?
Any help would be appreciated.
Why
When an entity is merged back into the EntityManager, it will be marked as dirty. This means that when a flush is performed, the entity will be updated in the database. This seems reasonable to me, because when you make an entity managed, you actually want the EntityManager to manage it ;)
In your case you only need the entity for an association with another entity, so you don't really need it to be managed. I therefor suggest a different approach.
Use a reference
So don't merge $contest back into the EntityManager, but grab a reference to it:
$contest = $cacheDriver->fetch($key);
$contestRef = $em->getReference('Contest', $contest->getId());
$contestRegistry = new ContestRegistry();
$contestRegistry->setContest($contestRef);
$em->persist($contestRegistry);
$em->flush();
That reference will be a Proxy (unless it's already managed), and won't be loaded from the db at all (not even when flushing the EntityManager).
Result Cache
In stead of using you own caching mechanisms, you could use Doctrine's result cache. It caches the query results in order to prevent a trip to the database, but (if I'm not mistaken) still hydrates those results. This prevents a lot of issues that you can get with caching entities themselves.
What you want to achieve is called partial update.
You should use something like this instead
/**
* Partially updates an entity
*
* #param Object $entity The entity to update
* #param Request $request
*/
protected function partialUpdate($entity, $request)
{
$parameters = $request->request->all();
$accessor = PropertyAccess::createPropertyAccessor();
foreach ($parameters as $key => $parameter) {
$accessor->setValue($entity, $key, $parameter);
}
}
Merge requires the whole entity to be 100% fullfilled with data.
I haven't checked the behavior with children (many to one, one to one, and so on) relations yet.
Partial update is usually used on PATCH (or PUT) on a Rest API.

doctrine 2 ODM preventing duplicate record

Doctrine NOOB here, trying to figure out how to prevent a duplicate record in an embed many property. I have a EmbededDocment like this:
<?
/**
* #EmbeddedDocument
*/
class Contact {
/**
* #Id
*/
private $id;
/**
* created timestamp
* #Date
*/
private $created;
/**
* modified timestamp
* #Date
*/
private $modified;
/**
* #String
*/
private $name;
/**
* #String
*/
private $name;
/**
* #String
*/
private $address;
}
what I want to happen is when I add a new contact, two contacts can have the same name, two contacts can have the same address, but two contacts can not have the same name and address. When checking for duplicates, doctrine will need to ignore the $id, $created and $modified properties as these will almost always be distinct. It is the combination of all the other fields that must be unique. How can this be accomplished using doctrine? Does this logic belong in a service layer or can doctrine do it for me?
UPDATE:
I do accept that Andrew's answer is the correct way to check for duplication using Mongo, I really want to know if doctrine can do this for me. Therefore, I'm starting a bounty.
You could implement an event listener which will listen to an preUpdate and prePersist event.
http://www.doctrine-project.org/docs/mongodb_odm/1.0/en/reference/events.html
In your event, you can do your own check.
You should validate your document before save it.
For example if user adding Contact with name="Name" and address="Address" you shoud check in mongodb if such Contact exists. And in case if it exists you just showing validation message, otherwise you adding contact to embedded contacts array.
So, suppose you have collection of users that's contains embedded array of contacts. To verify that new contact exists/not exists you can send request like this:
db.users.find({ userId: "userId" ,
contacts.name: "new contact name",
contacts.address: "new contact address"}).count();
If above query will return count >= 1 you no need add new contact, just show validation.

Categories