开发者

Retrieving data from a has_many relationship in DBIx::Class

开发者 https://www.devze.com 2023-01-09 00:20 出处:网络
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 so

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->result开发者_开发问答set('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.


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.


DBIx::Class::Manual::Joining should help. See, for example, Whole related objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消