1

I have a parent child entity relationship which is driven by a REST API. The payload contains data for both the parent and the child. The parent can have many children.

When the (child) payload is posted the API first checks if the parent exists (based solely on an ID value in the payload). If it does exist, that parent entity is assigned to an entityref field when the child entity is created. If the parent doesn't exist; it is created and the newly created parent is assigned to the child.

This works great.. until. It seems now that the API user is publishing multiple children with the same parent at the same time (I assume some sort of multi-threaded process). So the breakdown occurs when the first 2 children are created (at the "same time") and they both determine there is no existing parent; and then create duplicate parents.

Is there some Drupal db method that allows me to lock creation of a certain entity type; triggered by the first spot in the API code where the parent is to be created? I assume they are not exactly the same time; but they are within 1 second of each other and more precisely they are within the time it takes to create the first parent. Perhaps even a REST function to handle threaded calls?

3
  • 3
    Yes there's a nice neat built in locking mechanism: api.drupal.org/api/drupal/…, if you're using the core rest module you should be able to use hook_rest_resource_alter and override the resource class, where you can implement the lock – Clive Feb 17 at 21:47
  • Wow, nice API. I didn't know about this one! – Jaypan Feb 17 at 23:31
  • Thanks Clive; this looks like it should work. Just testing it out now. – liquidcms Feb 17 at 23:48
0

Does not sound like a multi-threading issue to me?

If you have two childs having the the same new parent in the entity reference field (BTW, what approach do use for creation, this is rather tricky ..), it will be probably created "twice", but with different ids - no?

Why don't you create the parent entity first and assign it afterwards to the entity-reference field target_id or entity property (if you are controlling it yourself)?

1
  • Yes, i had suggested the idea of creating the parent first; but doesn't fit well with the user's process. – liquidcms Feb 17 at 23:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.