What is the best way to model user defined hierarchical relationships in a database?

后端 未结 3 403
一生所求
一生所求 2021-02-04 22:08

Essentially, I want the user to be able to define a hierarchical model, but then I need to allow the user to store data within their defined model. Does this make sense? So the

3条回答
  •  有刺的猬
    2021-02-04 22:44

    You need to implement three concepts:

    • the "unit types" and their allowed associations
    • the hierarchy
    • the actual units

    These concepts can coexist more or less independently in the model, but work together.

    create table unittype
    (
        id int;
        name varchar(20);
    )
    
    create table unitrelationship
    (
        id int;
        parent_id int;
    )
    

    You could model the hierarchy as self-referencing table:

    create table hierarchy
    (
        id int;
        parent_id int;
        unit_type_id int;
        unit_id int;
    )
    

    You can then have your unit instances in one or more tables and do with them what you described.

    create table unit
    {
        id int;
        ....
    }
    

    The good news is that you are constraining only the allowed parent types, which can be easily enforced in a user interface, for instance by picking the parent from a list of all existing units of the allowed type.

提交回复
热议问题