Filina Consulting, Inc.

Forcing Doctrine to Persist

August 12th, 2015

I stumbled upon a case where Doctrine would refuse to persist my entity due to a very special circumstance. Here's the context: I'm using a generic method in my Repository to fetch a Post. I'm selecting partial fields like this:

SELECT PARTIAL post.{id, name} ...

If the entity is found, then I proceed to delete it by setting is_deleted to true, persisting and then flushing:

$post->is_deleted = true;
$this->getEntityManager()->persist($post);
$this->getEntityManager()->flush();

It doesn't save the entity. It skips it entirely. The column is mapped though. The problem is that the UnitOfWork checks the new data against the originally loaded data, then skips the fields that were not originally loaded. This seems to be the intended behavior. This in turn causes the whole entity to be skipped. I even tried selecting the column as HIDDEN (a DQL keyword), still no luck. In contrast, if I were to update the "name" property, it would have saved, because it was loaded in the SELECT.

Thankfully, the UnitOfWork has a public method that deals with it:

$this->getEntityManager()->getUnitOfWork()->setOriginalEntityProperty(spl_object_hash($post), 'is_deleted', false);

The hash refers to the specific instance, then you provide the mapped property name and the value. The value must be different from the one that you're setting later, otherwise it will also be skipped. Call this just before setting/persisting/flushing and you're in business.

Comments

webDEVILopers August 13th, 2015 At first I thought PARTIALS could be the cause. But at the bottom line it is the way Doctrine detects changes with the UnitOfWork:
http://doctrine-orm.readthedocs.org/en/latest/reference/unitofwork.html#how-doctrine-detects-changes

The same scenario makes lifecycle callbacks like `preUpdate` fail too btw.

Interesting fact that HIDDEN didn't work either. So the column doesn't get mapped at all and is only used for the DQL to execute the query?
Anna August 13th, 2015 HIDDEN's purpose is generally to compute a value to be used as sorting. Example: ... AS score HIDDEN ... ORDER BY score. So it makes sense that it won't be in the original data.

I think the reason partials have this update issue is because they were meant for reading operations, but not for writing back. Although it would make sense to *not* load all the data if you're overriding everything anyway, like when you receive data through an API. Perhaps ->persist($entity, $force_update) or something of the sort would be useful.

Or perhaps the Doctrine team has a better idea of how to merge JSON data into an entity.
nimasdj August 21st, 2015 When data is not changed why do you need to persist it again?
Anna August 21st, 2015 Data is changed, but Doctrine does not see it as changed. It's all in the article.
Mike Simonson September 13th, 2015 When you say The value must be different from the one that you’re setting later, otherwise it will also be skipped.

Do you mean that you are setting the value of is_deleted on that entity to false then calling $post->is_deleted = true; and that the change in the property value will trigger the fact that it will be taken into account for the persist call ?
Anna September 14th, 2015 Yes. I set it to false using setOriginalEntityProperty, then set it to true normally. Note that setting it to false normally, without going through the setOriginalEntityProperty method, will cause the entity to not be saved.
Tgabi333 September 14th, 2015 If you call $post->setIsDeleted(true) would load the full entity and after that doctrine would catch the change, isn't it?
Anna September 16th, 2015 It doesn't load the full entity when you do that. In any case, when loading a partial, it makes no sense to then load the full entity. That would defy the point of loading a partial.
TopasokDup December 13th, 2018 Качественную обувь всегда трудно найти. Связано это прежде всего с тем, что модные кроссовки дорогие, а подобрать что-то модное по оптимальной цене всегда тяжко. Если вы не представляете, в каком магазине заказать кроссовки, предлагаем рассмотреть возможность покупки кроссовок в интернет-магазинах.

Интернет-магазин фирменных кроссовок New Balance Sneakers-Top.ru

На данный момент стильные кроссы вы можете подобрать на купить мужские кроссовки кожаные где есть огромное количество кроссовок разных размеров и цветов. Интернет-магазин есть дисконтным, из-за этого цены в нём приемлемые. На сайте есть много кроссовок для парней и женщин. Вы можете найти отклики покупателей, которые приобретали разные кроссовки Nike и Puma.

Если вас заинтересовала какая-то конкретная модель, вы можете сделать звонок по телефону 8-(800)-111-22-33, где вам всё подскажут. На портале находится много кроссовок разных моделей. Вы можете найти в компании кроссовки для спорта или классические варианты.

На портале москва кроссовки адидас купить находится возможность купить кроссы разных брендов. Вы можете также пройти регистрацию и подписаться на рассылку. Благодаря этому вы сможете узнавать одним из первых о всех скидочных предложениях портала.

Приобрести брендовые мужские и женские кроссовки в Москве

В наши дни приобрести оригинальные кроссы в МО не так уж и легко. Нужно ехать в ТЦ, где цены очень сильно высокие. Чтобы не платить двойную стоимость в фирменных магазинах, оригинальные кроссовки вы можете купить и через сеть. В организации очень много вариантов разных брендов. Если вас интересует определенная модель из новой коллекции, вам её помогут подобрать.

Если вы желаете заказать по скидке кроссовки из старой коллекции, это также реально. В организации моментальная доставка. После того, как вы оформите заказ, с вами установит связь консультант и уточнит адрес доставки. Нужно выделить, что доставка по столице происходит в день заказа.

На фирменные кроссовки Adidas и New Balance часто проходят акции. Купить кроссовки Nike вы можете на ресурсе со скидкой. На некоторые модели скидка может доходить до -50%. Более подробную стоимость подсказать вам смогут консультанты интернет-магазина. Если вам не подойдёт какая-то определенная модель после доставки, вы её можете также вернуть. Возврат товара проходит невероятно быстро.

Оплату вы можете провести через банк. При желании оформить заказ вы можете позвонив в контакт-центр или через веб-портал, перейдя на Sneakers-Top.ru, где оформление заявки на покупку проходит очень быстро.
AsyertSkece December 18th, 2018 How Installment Loans May Help?

When you require money at the moment, the most trustworthy method to get it is to apply for installment loans which have been historically reputed as the most useful and timely for huge buyings. In this case, installment loan passes for a time-limited lend, meaning an indicated period for beginning and ending, which must be identified during the application process. That is you who think how frequently you should return the money. As an example, everyone might take the loan, being performed as a payment per month with 36 the same portions during two years.

Taking into account varieties of installment loans, you can take out between unsecured and secured one. Unsecured type is signature loan as it can be registered only by signing the agreement and justifying your readiness in such a way. Secured loan should be upheld by bail that should be seized in the event of unexpected consequences. For example, car loan is usually supported by the auto you borrowed ready money for. That's why bad credit installment loans in ND are considered as a real way-out to borrow cash on moderate terms.

How to Apply for Installment Loans when Your Credit Score Is Not Good?

Frankly speaking, you pop up from only two ways. The 1st one means to come in a bank. Nevertheless, take account that the causes for taking installment loans are a bit confined: private, mortgage, educational, and auto loans. To add to it, banking establishments have strict specifications for these borrowings, especially when you need an unsecured one. Lenders with marginal form of credit have to find a co-signer that has to be creditworthy and trusty. Moreover, banking institutions demand a long and time-taking application that won't correspond if you are in a hurry.

Another way-out and working solution in that case is to turn to our customizable services and have installment loans without queues and difficulties. We ensure the most appropriate terms for your precise state of affairs, providing great advantages and privileges. You can check it!

Advantages of Taking Installment Loans in Our Company

Owing to us, you should count on the following advantages:
Simple and quick|Fast and simple. Our company appreciates your time and wants to save it by offering convenient online application. As you can't afford yourself to wait for whole weeks to get an approval and take your money , we render up-to-date replies and variants from direct lenders.

Cash at hand. Our requirements are flexible and customizable; thus, we dispose a transparent working scheme with no extra fees, meaning that we render money support in case if you require it above all without any questions.

Lenders for your situation. We cooperate with trusty and checked lenders from the United States, who want to assist you!|

Bad credit history is not the last sentence. While many banks and creditors turn your loan down, we will make all efforts to pop up the most fitting decision for you. We appreciate every our client and would like to provide an individual attitude!

Charges you will afford. Do you remember these large rates, examining rivals' portals? We are aware of them as well! For this reason, we prefer to worry about clients than to raise money on their problems.

No checks of your credits. We realize why you've found us; thus, we don't pay attention to your credit score by offering you an opportunity not only to dispose cash but improve your credit score for the future, showing what a dependable debtor you are!

Think about Installment Loans?

Don't have doubts and keep in touch us to get more details about installment loans and terms https://maybeloan.com/installment-loans/vt-usa-il . Our consultants are available on twenty-four-hour basis and usually wish to assist you and so you will see a reply as soon as possible. Don't try to wait for the better times to have cash, assume them right now with our company!

Phone: +1 514-918-7866 | E-mail: me@afilina.com