DBIx::Class - add a read-only synthesized column (defined by SQL) to a result class?
Is it possible to add a 'synthesized' column to a DBIx::Class result class? The value of the synthesized column would be defined by a SQL expression of the current row. For example, if a row had the columns first
and last
, I could synthesize a new read-only column whose definition is \"me.first || ' ' || me.last"
(this is Oracle SQL syntax).
Close to what I want is listed under "COMPUTED COLUMNS" in the DBIx::Cla开发者_如何转开发ss documentation. However, in that case it seems that the column is already defined on the database side. My synthesized column is not in the table schema.
Failing that, is it possible to add my SQL expression to the generated SELECT
statement when I search the resultset?
(The above example SQL is misleading - I need to execute a SQL expression that involves database functions so I can't just implement it in perl.)
Perhaps I'm missing something, but I don't see why you can't just add a method to your result class like this:
sub name {
my $self = shift;
return $self->first . ' ' . $self->last;
}
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...
精彩评论