由于历史原因,我们有一个工作中的表,其文本字段中的整数值与另一个表中的 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/