2

是否可以将“合成”列添加到 DBIx::Class 结果类?合成列的值将由当前行的 SQL 表达式定义。例如,如果一行有 和 列firstlast我可以合成一个新的只读列,其定义为 \"me.first || ' ' || me.last"(这是 Oracle SQL 语法)。

DBIx::Class 文档中的“COMPUTED COLUMNS”下列出了接近我想要的内容。但是,在这种情况下,该列似乎已在数据库端定义。我的合成列不在表模式中。

如果做不到这一点,是否可以SELECT在搜索结果集时将我的 SQL 表达式添加到生成的语句中?

(上面的示例 SQL 具有误导性——我需要执行一个涉及数据库函数的 SQL 表达式,所以我不能只在 perl 中实现它。)

4

2 回答 2

3

也许我遗漏了一些东西,但我不明白为什么你不能像这样向结果类添加一个方法:

sub name {
  my $self = shift;

  return $self->first . ' ' . $self->last;
}
于 2011-10-05T09:11:50.637 回答
2

If the calculation must be done on the database side (after your earlier comment), then use the temporary column idea that i suggested, together with some direct SQL. Assuming that you don't wish to search on the field, then something like the following should work:

my $rs = My::Schema->resultset('people');

my @columns_as = $rs->result_source->columns;
my @columns = map { "me.$_" } @columns_as; 

my @people = $rs->search(
   { ... where conditions here ... },
   {
      select => [ @columns, \"me.first || ' ' || me.last" ],  # scalar ref for direct SQL
      as     => [ @columns_as, 'full_name' ],
      order_by => 'full_name',
      ... etc ...
   }
);

# then
print $_->full_name."\n" foreach @people; # now set on the object...

It should theoretically be possible to just specify your additional select and as columns using +select and +as, but I was unable to get these to work properly (this was a year or so ago). Can't recall exactly why now...

于 2011-10-06T09:50:03.123 回答