2010-03-01 159 views
2

在我的代码有三个类,如下所示:ForumForum::ThreadForum::Post如何使用DBIx :: Class创建嵌套的has_many或belongs_to关系?

我想要做的就是创建一个从Forum::Post类的Forum类,反之亦然用的has_many一个belongs_to的关系,最好而无需为其创建自定义功能。 (这当然是更多的智力练习,而不是技术限制或实际问题,但如果可能的话,我很想知道。)

注释掉的行包含我关于关系的意图,但是在它们的当前形式,他们失败了。我在文档中探索过,但找不到与此特定案例相关的任何内容。

任何指针?

论坛等级:

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; 

Thread类:

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; 

Post类:

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:附加列,持有的实际内容进行了省略简洁。

+0

你有什么期望这个嵌套关系呢?在这些情况下'$ post-> forum'或$ forum-> post'是什么意思?你不能只使用'$ post-> thread-> forum'和'为我的$ thread($ forum-> threads){为我的$ post($ thread-> posts){}}'做你想做的事? – 2010-03-03 17:59:04

+0

@Phillip Potter:我有点担心过期;我最终想用'$ forum-> posts'实现的是*一个* SQL查询,它提取所有数据。 $ post-> forum实际上只是$ post-> thread-> forum的简写,所以我认为这不太有趣。 – 2010-03-04 12:17:25

+0

我建议你订阅DBIx :: Class邮件列表并在那里询问。我不确定如何去做你所要求的。 – 2010-03-07 07:58:46

回答

1

它看起来像嵌套关系是不可能的。 has_many接受一个外部类,它具有调用类的外键。

好消息是$forum->threads->posts返回单个DBIx::Class::Resultset。它在需要之前不会被翻译成SQL,因此当您拨打$forum->threads->posts->all()或甚至像$forum->search_related('threads',{},{rows=>25})->posts->all()这样的内容时,它只会运行一个查询。

如果你的目标是有一个$后>的论坛,它可以永远是一个方法:sub forum{$_[0]->thread->forum}

0

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

相关问题