douju3911 2013-06-13 11:26
浏览 40
已采纳

Kohana 3.3表结构

I have a simple crud application in Kohana 3.3, with a few different types of data or models. Let’s say those models are:

  • Users
  • Locations
  • Skills

I have a table for each of those models, but the tables aren’t related to one another in any way. I’ve been trying to define relationships with ORM, but I’m still confused. As an example:

I have a number of locations. Each location has many users.

I know I can define that with:

class Model_Location extends ORM {

    /**
     * A location has many users
     *
     * @var array Relationships
     */
    protected $_has_many = array(
        'users' => array('model' => 'user'),
    );

}

As I understand it, I can connect the two by referencing the ID of the parent location from the row in the user table. However, what if each user can belong to many locations? Am I supposed to store serialised data in a foreign key? Should I create a “look-up table”? If so, how should it look?

How can I for example, query the database for a location and all users attached to it? Is ORM even the right technology to be using for this kind of thing?

  • 写回答

1条回答 默认 最新

  • dqsa17330 2013-06-13 11:41
    关注

    You are looking for the through parameter, have a look at the docs.

    You need an extra table that stores the ids of both models

    table users_locations, fields: user_id and location_id (both indexed, of course)

    And in your model:

    protected $_has_many = array(
        'users' => array(
            'model' => 'user'
            'through' => 'users_locations',
        ),
    );
    

    And vice versa in the user model:

    protected $_has_many = array(
        'locations' => array(
            'model' => 'location'
            'through' => 'users_locations',
        ),
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看