2

在我的代码中,我有以下三个类:ForumForum::ThreadForum::Post

我想要做的是创建一个从Forum::Post类到Forum类的belongs_to-relationship,反之亦然,使用has_many,最好不为其创建自定义函数。(诚​​然,这更像是一种智力练习,而不是技术限制或实际问题,但如果可能的话,我很想知道。)

注释掉的行包含我对关系的意图,但在目前的形式下,它们无法工作。我在文档中四处寻找,但找不到与此特定案例相关的任何内容。

任何指针?

论坛类:

package Schema::Result::Forum;

use Moose;
extends qw/DBIx::Class/;

__PACKAGE__->load_components (qw/Core/);
__PACKAGE__->table ('forum');

__PACKAGE__->add_columns (
    id => {
    is_auto_increment => 1,
    data_type         => 'integer',
  },
);

__PACKAGE__->set_primary_key ('id');

__PACKAGE__->has_many (threads => 'Schema::Result::Forum::Thread');
#This is the interesting line
#__PACKAGE__->has_many (posts => 'threads' => 'forums' );

1;

线程类:

package Schema::Result::Forum::Thread;

use Moose;
extends qw/DBIx::Class/;

__PACKAGE__->load_components (qw/Core/);
__PACKAGE__->table ('forum_thread');
__PACKAGE__->add_columns (
  id => {
    is_auto_increment => 1,
    data_type         => 'integer',
  },
  forum => {
    data_type         => 'integer',
  },
);

__PACKAGE__->set_primary_key ('id');

__PACKAGE__->belongs_to (forum => 'Schema::Result::Forum');
__PACKAGE__->has_many (posts => 'Schema::Result::Forum::Post');

1;

帖子类:

package Schema::Result::Forum::Post;

use Moose;

extends qw/DBIx::Class/;

__PACKAGE__->load_components (qw/Core/);

__PACKAGE__->table ('forum_post');

__PACKAGE__->add_columns (
  id => {
    is_auto_increment => 1,
    data_type         => 'integer',
  },
  thread => {
    data_type         => 'integer',
  },
);

__PACKAGE__->set_primary_key ('id');

__PACKAGE__->belongs_to (thread => 'Schema::Result::Forum::Thread');
#This is the other interesting line
#__PACKAGE__->belongs_to (forum => 'thread' => 'forum');

1;

PS:为简洁起见,省略了包含实际内容的其他列。

4

2 回答 2

1

看起来嵌套关系是不可能的。has_many 采用单个外部类,该类具有调用类的外键。

好消息是$forum->threads->posts返回单DBIx::Class::Resultset。它在需要之前不会被翻译成 SQL,所以当你调用$forum->threads->posts->all()或什至类似的东西时$forum->search_related('threads',{},{rows=>25})->posts->all(),它只运行一个查询。

如果你的目标是拥有一个 $post->forum,它总是可以是一个方法:sub forum{$_[0]->thread->forum}

于 2010-03-19T05:31:53.473 回答
0

您使用的是什么数据库和引擎类型?如果您没有外键(例如 MySQL 中的 myisam 表),那么您必须在关系语句中提供列名。

于 2010-03-17T18:51:59.693 回答