Search code examples
perldbix-class

Why does DBIx::Class not create many-to-many accessors?


While creating a schema from a database many-to-many relationships between tables are not created.

Is this a principal problem?

Is it possible to detect from the table structure that many-to-many relationships exist and create the respective code in schema classes automagically?


Solution

  • The problem with developing this kind of code is that many tables that contain multiple references are not many-to-many tables, and have multiple references for other reasons. For instance, I'll make up a schema for some fictional app where something could be regarded as a many-to-many table, when it is not.

    create table category (
        id primary key,
        ...
    );
    
    create table sub_category (
        id primary key,
        category references category(id),
        ...
    );
    
    /* EDIT:
        This is the table that could be regarded as many_to_many
        by an automated system */
    create table product (
        id primary key,
        category references category(id),
        sub_category references sub_category(id),
        ...
    );
    

    Something could be built this way for ease of use, without having to do multiple table joins in the database on a website, especially when considering speed. It would be difficult for a piece of code to say definitively 'this is not a many_to_many' situation, while the developer should be able to easily figure it out, and add in the many_to_many line below the checksum.

    I consider DBIX::Class schema outputs a good starting point, and little more, especially when working with auto numbering in non-MySQL databases, among other things. I often need to modify above the "Don't modify above this line" stuff (although many_to_many can obviously go below that checksum, of course.