perl - 在 DBIx::Class 中将 CAST(foo AS type) 作为关系条件传递

标签 perl postgresql dbix-class

由于历史原因,我们有一个工作中的表,其文本字段中的整数值与另一个表中的 ID 相对应。示例:

CREATE TABLE things (
    id     INTEGER,
    name   VARCHAR,
    thingy VARCHAR
);

CREATE TABLE other_things (
    id     INTEGER,
    name   VARCHAR,
);

所以一个“东西”有一个“其他东西”,但不是合理设置,连接字段是一个 varchar,称为“thingy”。

所以在 Postgres 中,我可以这样做来连接两个表:

SELECT t.id, t.name, ot.name FROM things t 
  JOIN other_things ot ON CAST(t.thingy AS int) = ot.id

我如何在 DBIx::Class 中表示这种关系?这是我尝试过的一件事的示例:

package MySchema::Thing;

__PACKAGE__->has_one(
    'other_thing',
    'MySchema::OtherThing',
    { 'foreign.id' => 'CAST(self.thingy AS int)' },
); 

最佳答案

nwellnhof 很接近,但要将文字 SQL 转换为 SQL::Abstract,我必须像这样执行代码引用:

__PACKAGE__->has_one(
    'other_thing',
    'MySchema::OtherThing',
    sub {
        my $args = shift;
        return {
            qq{$args->{'foreign_alias'}.id} => { q{=} => \qq{CAST($args->{'self_alias'}.dept AS int)} },
        };  
    },
); 

关于perl - 在 DBIx::Class 中将 CAST(foo AS type) 作为关系条件传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18905146/

相关文章:

c - PostgreSQL - 在 C 函数中使用日期常量

postgresql - Perl DBIx::Class:从数据库获取当前时间

postgresql - microk8s集群中如何访问本地安装的postgresql

linux - 脚本无法确认文件夹,即使它们存在

python - BitTorrent 跟踪器 API 不错吗?

regex - 调试 Perl 正则表达式

database - 授予对 future 在 PostgreSQL 中创建的模式的使用权和特权

perl - 如何为 DBIx 类部署测试数据库

perl - 为 Dancer2 配置 Test::DBIx::Class::Schema 到应用程序

arrays - 如何使对象成为数组引用?