【问题标题】:ORM relationships in KohanaKohana 中的 ORM 关系
【发布时间】:2010-11-03 10:26:43
【问题描述】:

我有以下表格:

users           { id, name }
events          { id, name }
user_events     { id, date, user_id, event_id }
user_summaries  { id, user_id, event_id, qty }

user_events 存储所有用户事件(在不同时间有许多相同的类型),user_summaries 存储每个用户发生的每种类型事件的数量。前者仅获得INSERT 查询,而后者主要获得UPDATE 查询。

当然user_eventsuser_summaries 都有外键来链接usersevents 表。 我想在我的 Kohana 模型中表示这种关系。我有使用外键的经验,但这是我第一次使用 Kohana 和 ORM 的方法,我不确定如何在那里定义我的模型来表示这些关系。

我想做的基本上是这样的:

// I'm able to do this.
$user = ORM::factory('user', 1);
$user_events = $user->events->find_all();
$user_summaries = $user->usersummaries->find_all();

// I'm able to do this, too.
$event = ORM::factory('event', 1);
$event_users = $event->users->get_all();

// I don't know how to be able to do this:
$user_event = ORM::factory('userevent', 1);
$user_details = $user_event->user->find();
$event_details = $user_event->event->find();

我当前的模型如下所示:

# classes/model/user.php
class Model_User extends ORM
{
    protected $_has_many = array(
        'scores'    => array(),
        'usersummaries' => array(),
    );
}

# classes/model/event.php
class Model_Event extends ORM
{
    protected $_has_many = array(
        'scores'        => array(),
        'usersummaries' => array(),
    );
}

# classes/model/userevent.php
class Model_Userevent extends ORM
{
    protected $_belongs_to = array(
        'user'  => array(),
        'event' => array(),
    );
}

# classes/model/usersummary.php
class Model_Usersummary extends ORM
{
    protected $_belongs_to = array(
        'user'  => array(),
        'event' => array(),
    );
}

当前调用:

$user_event = ORM::factory('userevent', 1);
$user_details = $user_event->user->find();

总是返回来自users 表的第一个用户,即使userevent 有不同的user_id。 我想我需要更改 Model_userevent 中的某些内容,但我会在一些帮助下使用。

注意。我正在使用 Kohana 3.0.8。

【问题讨论】:

  • 使用$user_event->user(没有find())。模型看起来不错,但您可能应该手动为 usersummariesuserevents 关系定义相关模型(Ko3 变形器可能对这些名称不起作用)
  • 我怎么没想到!谢谢你,比亚克维隆。把它作为答案,这样我就可以接受了。

标签: orm kohana-3 kohana-orm


【解决方案1】:

使用$user_event->user(不带find())。模型看起来不错,但您可能应该手动为 usersummariesuserevents 关系定义相关模型(Ko3 变形器可能对这些名称不起作用)

【讨论】:

    猜你喜欢
    • 2013-01-27
    • 2011-03-24
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多