How to insert in a database elements with links to

2019-07-25 02:04发布

问题:

I need to sequentially insert several objects in a SQL database, each of them containing a string of text. This string may have a special segment denoted by brackets, anywhere in the text, that represents a link to a different object. This "target" object may be of the same "text" type, or a different one, corresponding to a different table in the database. Since the objects are inserted sequentially, the target object may be already inserted or not.

My question is: what would be the best way to reference this target object in the text? So far, I can see the following options:

  1. Using the id of the destination object: This would be ideal, but I don't know the id that the object will have before I insert it (it's auto generated, and needs to be for reasons outside the scope of the problem). Using this method would require inserting all the objects with temporary codes in the links positions, and then updating all the ones with links, changing the temporary code with the correct id.
  2. Using a code, different from the normal id: This would require all of the potential targets to include an extra field with this "code". This seems artificial and unnecessary, but is my best option so far.

I'm looking for a better alternative to the ones that I've found, since none of them seem entirely "correct": the first one requires a lot of updates to already inserted elements, and the second one involves artificially cluttering several tables of an already established database. Any ideas?