别名DBIx :: Class结果集中两列的总和

时间:2014-02-27 01:16:18

标签: perl alias dbix-class

  

选择me.id,me.date_created,me.date_updated,me.yes,   me.name,me.description,me.currency,me.locked,me.skip,   me.uri_part,me.user_id,   是+货币作为重量

     

来自我的想法((重量<5))按重量排序;

如何在不使用文字SQL的情况下在DBIx :: Class中生成该查询:

    my $query = $rs->search({},
    {
        '+select' => \[
            'yes + currency as weight',
        ],
        rows => 1,
        order_by => { -desc => [qw/weight name/] },
        having => {
            weight => { '<' => $self->yes + $self->currency },
        },
    });
    use Data::Dumper;
    warn Dumper($query->as_query);

我尝试使用-as,但它似乎只对使用函数生成的列有用,如下所示:

'+select' =>  {
  'yes + currency', '-as' => 'weight'
}

生成错误

  

“匿名哈希中的奇数元素数量   /data/TGC/lib/TGC/DB/Result/Idea.pm第105行,第1000行。   DBIx :: Class :: SQLMaker :: _ recurse_fields():格式错误的选择参数 -   哈希中的密钥太多:SCALAR(0xbf14c40),权重“

2 个答案:

答案 0 :(得分:3)

可能是我在SQL Abstract表达式中可以想到的最惯用的东西,没有太过紧张:

#!/usr/bin/env perl
use Modern::Perl;

use MySchema;
use Data::Dumper;

my $schema = MySchema->connect('dbi:SQLite:example.db');

my $rs = $schema->resultset('Sample')->search(
  {
     weight => { '<' => 5 },
  },
  {
    '+select' => [
        { '' => \'`me`.`yes` + `me`.`currency`', -as => 'weight' }
    ]
  }
);


say Dumper( $rs->as_query() );

这是一个设计的列名称包装,但它完成了这项工作。只是不知道抽象这里+的任何方式。但是,stil:

  

'(SELECT me.name,me.yes,me.currency,(me.yes + me.currency)AS weight FROM sample me WHERE(weight&lt;?))',

除非您只是选择惯用语perl,否则:

{ '' => \(join " + ", qw/`me`.`yes` `me`.`currency`/), -as => 'weight' }

但是考虑到两种形式都比文字字符串长,这两种方式似乎有点人为。

另请注意, WHERE 中引用了weight而非 HAVING ,这是因为在各种SQL引擎上爆炸

答案 1 :(得分:0)

'+ as'应与'+ select'

处于同一水平
$idea = $rs->search({-and => [
    name   => { '<' => $self->name },
]},
{
    '+select' => [
        'yes + currency'
    ],
    '+as' => [qw/weight/],
    rows => 1,
    order_by => ['weight', 'name'],
    having => {
        weight => { '<' => $self->yes + $self->currency },
    },
})->single;