views:

72

answers:

1

I'm working on building an app with Kohana 3.0.7, using the ORM module. I want to build an object, such as tag, where many different kinds of objects can be tagged, and these options can have multiple tags. So let's say for example I have 3 models: Tag, Post and Page. how would I structure the tables and the models to make this work best?

+1  A: 

You'd use Kohana's has-many-through relationship. An example would be:

class Model_Page
{
    protected $_has_many = array(
        'tags' => array(
            'model' => 'tag',
            'foreign_key' => 'page_id',
            'far_key' => 'tag_id',
            'through' => 'pages_tags',
        ),
    );
}

class Model_Post
{
    protected $_has_many = array(
        'tags' => array(
            'model' => 'tag',
            'foreign_key' => 'post_id',
            'far_key' => 'tag_id',
            'through' => 'posts_tags',
        ),
    );
}

class Model_Tag
{
    protected $_has_many = array(
        'pages' => array(
            'model' => 'page',
            'foreign_key' => 'tag_id',
            'far_key' => 'page_id',
            'through' => 'pages_tags',
        ),
        'posts' => array(
            'model' => 'post',
            'foreign_key' => 'tag_id',
            'far_key' => 'post_id',
            'through' => 'posts_tags',
        ),
    );
}
Zahymaka