代码之家  ›  专栏  ›  技术社区  ›  Williham Totland

如何创建与dbix::类有多个或属于关系的嵌套?

  •  2
  • Williham Totland  · 技术社区  · 15 年前

    在我的代码中,我有三个类,如下所示: Forum , Forum::Thread Forum::Post

    我想做的是从 论坛:帖子 类到 论坛 类,反之亦然, 更可取地 没有为它创建自定义函数。(无可否认,这更多的是一种智力活动,而不是技术限制或实际问题,但如果可能的话,我很想知道。)

    注释行包含了我与这些关系的意图,但在它们当前的形式下,它们无法工作。我翻了一下文件,但找不到与这个具体案件有关的任何东西。

    有什么线索吗?

    论坛课程:

    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: 为简洁起见,省略了用于保存实际内容的其他列。

    2 回复  |  直到 15 年前
        1
  •  1
  •   zpmorgan    15 年前

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

    好消息是 $forum->threads->posts 返回单个 DBIx::Class::Resultset . 在需要时才将其转换为sql,因此当您调用 $forum->threads->posts->all() 或者类似的东西 $forum->search_related('threads',{},{rows=>25})->posts->all() ,它只运行一个查询。

    如果您的目标是拥有一个$post->论坛,它可以始终是一种方法: sub forum{$_[0]->thread->forum}

        2
  •  0
  •   c0bra    15 年前

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