从 DBIx::Class 中的 has_many 关系检索数据

发布于 2024-09-11 16:36:35 字数 548 浏览 3 评论 0原文

给定两个表的简单情况 - 术语和定义 - 其中术语 has_many 定义和定义 belongs_to 术语,所有术语和相应的定义都将以某种方式获取并显示。

这是我到目前为止所想到的:

my $terms= $schema->resultset('Term')->search(undef, {  
  prefetch => 'definitions',  
});  

while (my $term = $terms->next) {
  my @terms;
  push @terms, $term->term;

  my $definitions = $term->definitions;
  my @definitions;
  while (my $definition = $definitions->next) {
    push @definitions, $definitions;
  }
  ...
}

它可以完成工作,但我想知道是否可以采取不同的、不那么粗暴的方法。

Given a simple case of two tables - Term and Definition - where Term has_many Definitions and Definition belongs_to Term, all terms and the corresponding definitions are to be fetched and displayed somehow.

Here is what I've come up with so far:

my $terms= $schema->resultset('Term')->search(undef, {  
  prefetch => 'definitions',  
});  

while (my $term = $terms->next) {
  my @terms;
  push @terms, $term->term;

  my $definitions = $term->definitions;
  my @definitions;
  while (my $definition = $definitions->next) {
    push @definitions, $definitions;
  }
  ...
}

It does the job but I was wondering if a different, less crufty approach could be taken.

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

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

发布评论

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

评论(2

温柔女人霸气范 2024-09-18 16:36:35
my $terms= $schema->resultset('Term')->search(undef, {  
  prefetch => 'definitions',  
});  

my @terms = $terms->all;

my @definitions = map $_->definitions->all, @terms;

这看起来像你正在尝试做的事情;我实在说不出来。事实上,你创建一个新数组,推入它,然后让它超出范围,这一事实根本没有任何意义。无论如何,如果我理解正确的话,您想要的只是 DBIx::Class::ResultSet 中的 all 方法。

my $terms= $schema->resultset('Term')->search(undef, {  
  prefetch => 'definitions',  
});  

my @terms = $terms->all;

my @definitions = map $_->definitions->all, @terms;

This looks like what you are trying to do; I can't really tell. The fact that you make a new array, push onto it, and then let it go out of scope doesn't really make any sense at all. Anyway, if I understand you correctly all you wanted was the all method from DBIx::Class::ResultSet.

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