Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What you are describing is an acyclic directed graph, not a tree, so you can't use any of the sql "tree-storage" methods like MPTT. <a href="http://www.codeproject.com/Articles/22824/A-Model-to-Represent-Directed-Acyclic-Graphs-DAG-o" rel="nofollow">Here is an article that demonstrates an adjacency-list approach to this problem.</a></p> <p>I highly recommend that you do not go down this path, however, not because of the difficulty of implementation, but because you will end up confusing and frustrating your users. In my experience users make poor use of complex ontological systems and are easily confused by them. Either use a flat "tag" namespace with no parent-child relationships, or use a tree arrangement with at most one parent per node.</p> <p>But if you want to have a graph, he most straightforward way is to have a table like this:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE tag_relationships ( tag_child_id INTEGER NOT NULL REFERENCES tags (id) ON UPDATE CASCADE ON DELETE CASCADE, tag_parent_id INTEGER NOT NULL REFERENCES tags (id) ON UPDATE CASCADE ON DELETE CASCADE, PRIMARY KEY (tag_child_id, tag_parent_id) ); </code></pre> <p>You will probably not be able to avoid recursive queries. When you want to create a matching search, use the tags you have as search criteria and recursively add child tags until you have a complete tag list.</p> <p>You will also have to be careful about creating cycles. When you add a relationship, you need to recursively visit parents and make sure you don't end up at the same node twice.</p> <p>Something you can do to avoid recursive queries and help detect cycles is to denormalize your data a bit by making <em>all</em> relationships explicit for <em>every</em> node. What I mean is, suppose A is a child of B and C, and C is a child of D.</p> <p>Instead of the minimum number of edges necessary to represent this fact:</p> <pre><code>tag_child_id tag_parent_id A B A C C D </code></pre> <p>You would make all implicit relationships (ones you would have had to find via recursion) explicit:</p> <pre><code>A B A C A D C D </code></pre> <p>Notice that I added <code>(A, D)</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload