Search code examples
kohanakohana-3kohana-orm

Understanding Kohana ORM Relationships


I know this question has been asked a million times, but I can't seem to find one that really gives me a good understanding of how relationships work in Kohana's ORM Module.

I have a database with 5 tables:

approved_submissions
   -submission_id
   -contents

favorites
   -user_id
   -submission_id

ratings
   -user_id
   -submission_id
   -rating

users
   -user_id

votes
   -user_id
   -submission_id
   -vote

Right now, favorites,ratings, and votes have a Primary Key that consists of every column in the table, so as to prevent a user favoriting the same submission_id multiple times, a user voting on the same submission_id multiple times etc. I also believe these fields are set up using foreign keys that reference approved_submissions and users so as to prevent invalid data existing in the respective fields.

Using the DB module, I can access and update these tables no problem. I really feel as though ORM may offer a more powerful and accessible way to accomplish the same things using less code.

Can you demonstrate how I might update a user voting on a submission_id? A user removing a favorite submission_id? A user changing their rating on a particular submission_id?

Also, do I need to make changes to my database structure or is it okay the way it is?


Solution

  • You're probably looking for has_many_through relationships.

    So to add a new submission, you'd do something like

     $user->add('submissions', $submission);
    

    and to remove

     $user->remove('submissions', $submission);
    

    You may want to consider restructuring your database table and key names so you don't end up doing a lot of configuration.