如何在 Kohana 3 ORM 关系中指定两个键

发布于 2024-12-16 10:58:08 字数 183 浏览 5 评论 0原文

我有一个“答案”表和一个“用户”表。我需要链接它们,但我必须在两个表上使用自定义键(即我不在其中任何一个表中使用“id”)。两个表都有连接它们的“facebook_id”字段。

在答案模型中,我定义了一个“belongs_to”用户,并且可以定义答案的外键,但是我怎么能说“在两个表上使用 facebook_id 将答案链接到用户”呢?

I have a "answers" table and a "users" table. I need to link them but I have to use custom keys on both tables (i.e. I'm not using 'id' in any of them). Both tables have the "facebook_id" field which connects them.

In the Answer model I define a "belongs_to" User, and I can define Answer's foreign_key, but how can I say "link Answer to User using facebook_id on both tables"?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狼亦尘 2024-12-23 10:58:08

看来唯一可能的方法是将模型 _primary_key 更改为 facebook_id

在调查 ORM 类结构后,您会看到表像这样连接

    elseif (isset($this->_belongs_to[$column]))
    {
        $this->_load();

        $model = $this->_related($column);

        // Use this model's column and foreign model's primary key
        $col = $model->_table_name.'.'.$model->_primary_key;
        $val = $this->_object[$this->_belongs_to[$column]['foreign_key']];

        $model->where($col, '=', $val)->find();

        return $model;
    }

正如您所提到的你可以使用

protected $_belongs_to = array('user' => array('foreign_key' => 'facebook_id')

但这会导致

answers.id = users.facebook_id

但是如果你像这样将答案的主键从 id 更改为 facebook_id

protected $_primary_key = 'facebook_id';

那么当然最终查询会导致

answers.facebook_id = users.facebook_id

It appears the only way this is possible is by changing your models _primary_key to facebook_id

Upon investigation of the ORM class structure you'll see the tables are joined like so

    elseif (isset($this->_belongs_to[$column]))
    {
        $this->_load();

        $model = $this->_related($column);

        // Use this model's column and foreign model's primary key
        $col = $model->_table_name.'.'.$model->_primary_key;
        $val = $this->_object[$this->_belongs_to[$column]['foreign_key']];

        $model->where($col, '=', $val)->find();

        return $model;
    }

As you mentioned you can use

protected $_belongs_to = array('user' => array('foreign_key' => 'facebook_id')

But that would result in

answers.id = users.facebook_id

But if you change the primary key on answers from id to facebook_id like so

protected $_primary_key = 'facebook_id';

Then of course the final query would result in

answers.facebook_id = users.facebook_id
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文