如何使用外部数据过滤 DBIX::Class 结果集?
使用 DBIx::Class ,我有一个需要按数据过滤的结果集无法通过 SQL 生成。 我需要做的是与这个假设的例子有效等效的事情:
my $resultset = $schema->resultset('Service')->search(\%search);
my $new_resultset = $resultset->filter( sub {
my $web_service = shift;
return $web_service->is_available;
} );
通读文档让我不知道如何完成这样的策略。
Using DBIx::Class and I have a resultset which needs to be filtered by data which cannot be generated by SQL. What I need to do is something effectively equivalent to this hypothetical example:
my $resultset = $schema->resultset('Service')->search(\%search);
my $new_resultset = $resultset->filter( sub {
my $web_service = shift;
return $web_service->is_available;
} );
Reading through the docs gives me no clue how to accomplish a strategy like this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于 DBIC 结果集的设计目标,您实际上不能这样做:
允许通过在 Perl 端运行的代码进行过滤将使实现这些属性变得极其困难,并且会隐藏这样的结果集在组合时实际上运行 N 个查询的事实。
无论如何,你为什么想要这个? 为什么仅仅检索结果并自行过滤还不够?
封装? (例如,在业务逻辑层中隐藏过滤逻辑,但在显示逻辑层中启动查询。)然后编写一个自定义 ResultSet 子类,该子类具有一个运行查询并执行所需过滤的访问器。
开销? (例如,您将拒绝大多数结果,因此您不需要为它们创建对象的开销。)然后使用 HashRefInflator。
You can’t really, due to the goals for which DBIC result sets are designed:
Allowing filtering by code that runs on the Perl side would make it extremely hairy to achieve those properties, and would hide the fact that such result sets actually run N queries when composed.
Why do you want this, anyway? Why is simply retrieving the results and filtering them yourself insufficient?
Encapsulation? (Eg. hiding the filtering logic in your business logic layer but kicking off the query in the display logic layer.) Then write a custom ResultSet subclass that has an accessor that runs the query and does the desired filtering.
Overhead? (Eg. you will reject most results so you don’t want the overhead of creating objects for them.) Then use HashRefInflator.
如果您过滤结果并最终得到行列表,您可以创建一个新结果集,如下所示: http://search.cpan.org/~abraxxa/DBIx-Class-0.08127/lib/DBIx/Class/Manual/Cookbook.pod#Creating_a_result_set_from_a_set_of_rows。
这可能会保持结果作为结果集的一致性,但我想您将无法链接它或在其上使用任何其他结果集方法。
If you filter the results and end up with a list of rows you can create a new resultset like this: http://search.cpan.org/~abraxxa/DBIx-Class-0.08127/lib/DBIx/Class/Manual/Cookbook.pod#Creating_a_result_set_from_a_set_of_rows.
This may keep things consistent in keeping the results as a resultset but I imagine you would not be able to chain it or use any other resultset methods on it.