Search code examples
codeignitercodeigniter-datamapper

Mapping relationships to generic models in Datamapper for Codeigniter


I have a number of different models in a system backed by the Datamapper library for Codeigniter such as Posts and Pages and am interested in adding Likes and Comments to the system. The way I see it, Likes and Comments can apply to any sort of model that extends Datamapper. How would I go about defining such a relationship (keep Likes for any sort of model in the same table, as well as Comments)?


Solution

  • I tend to create separate tables for likes and comments. I usually create this sort of schema:

    Likes
    -----
    id      // autoincrement
    obj     // the related model (the name of the model that is being liked)
    obj_id  // the foreign key
    user_id // the user id that liked the model object
    created // timestamp
    updated // timestamp
    

    Then the comments table:

    Comments
    --------
    id       // autoincrement
    obj      // the related model (same as above)
    obj_id   // the foreign key
    message  // the comment itself
    user_id  // the user id that commented on the model object
    created  // timestamp
    updated  // timestamp