Modeling a many-to-many with multiple object types in Kohana w/ ORM

杀马特。学长 韩版系。学妹 提交于 2019-12-11 06:37:45

问题


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:


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',
        ),
    );
}


来源:https://stackoverflow.com/questions/3592101/modeling-a-many-to-many-with-multiple-object-types-in-kohana-w-orm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!