通过返回结果集而不是表或视图的mssql存储过程向我提供了从db读取的权限。但我希望能够使用ORM读取数据。
我尝试使用DBIx::Class::ResultSource::View
来执行过程调用(例如EXEC my_stored_proc ?
)作为自定义查询,但这不起作用,因为它试图将过程调用转换为select语句。
有没有人有其他建议?
答案 0 :(得分:6)
不,没有合理的方法在DBIx :: Class的上下文中执行存储过程。
据我所知,与解决方法最接近的是“使用ORM”获取数据库句柄,这是一个很弱的问题:
my @results = $schema->storage->dbh_do(sub{
my ($storage, $dbh, @args) = @_;
my $sth = $dbh->prepare('call storedProcNameFooBar()');
my @data;
$sth->execute();
while( my $row = $sth->fetchrow_hashref){
push @data, $row;
}
return @data;
},());
[详情见 http://metacpan.org/pod/DBIx::Class::Storage::DBI#dbh_do]
...因为你没有为你的麻烦获得ORM的任何好处。
答案 1 :(得分:-2)
您可以使用register_source
package My::Schema::User;
use base qw/DBIx::Class/;
# ->load_components, ->table, ->add_columns, etc.
# Make a new ResultSource based on the User class
my $source = __PACKAGE__->result_source_instance();
my $new_source = $source->new( $source );
$new_source->source_name( 'UserFriendsComplex' );
# Hand in your query as a scalar reference
# It will be added as a sub-select after FROM,
# so pay attention to the surrounding brackets!
$new_source->name( \<<SQL );
( SELECT u.* FROM user u
INNER JOIN user_friends f ON u.id = f.user_id
WHERE f.friend_user_id = ?
UNION
SELECT u.* FROM user u
INNER JOIN user_friends f ON u.id = f.friend_user_id
WHERE f.user_id = ? )
SQL
# Finally, register your new ResultSource with your Schema
My::Schema->register_source( 'UserFriendsComplex' => $new_source );
要使用参数调用,请执行以下操作
my $friends = [ $schema->resultset( 'UserFriendsComplex' )->search( {
+},
{
bind => [ 12345, 12345 ]
}
) ];