我有以下DBIx :: Class代码:
my $where = 'me.loginid = ? AND me.code = ?';
my @bind = ( $loginID, $code );
my $tip_signals = $bom_schema->resultset('Table1')->search_literal(
$where, @bind,
{
join => 'table2',
group_by => [ 'me.id' ],
'+select' => [ {'count' => '*'}, 'table2.id' ],
'+as' => [ 'Count', 'ID' ],
});
基于以上DBIx :: Class代码生成以下SQL语句:
SELECT me.id, me.loginid, me.tipster_date, me.code, me.short_code_without_payout, COUNT( * ), table2.id
FROM table1 me LEFT JOIN table2 table2 ON table2.tip_signals_id = me.id
WHERE (
me.loginid = 'yccheok' AND me.code = 'ALIBABA_CODE'
)
GROUP BY me.id
现在,我希望得到4个表的结果。我手动编写自己的SQL代码:
SELECT me.id, me.loginid, me.tipster_date, me.code, me.short_code_without_payout, COUNT( * ), table2.id
FROM table1 me, table2, referrers, affiliates
WHERE (
me.loginid = 'yccheok' AND me.code = 'ALIBABA_CODE'
and table2.tip_signals_id = me.id
and referrers.affiliates_id = affiliates.id
and affiliates.loginid = me.loginid
and referrers.loginid = table2.loginid
)
GROUP BY me.id
我尝试将上面的SQL语句翻译成DBIx :: Class,如下所示:
my $where = 'me.loginid = ? AND me.code = ? AND table2.tip_signals_id = me.id AND referrers.affiliates_id = affiliates.id AND affiliates.loginid = me.loginid AND referrers.loginid = table2.loginid';
my @bind = ( $loginID, $code );
my $tip_signals = $bom_schema->resultset('Table1')->search_literal(
$where, @bind,
{
from => [ {table2=>'table2'}, {referrers=>'referrers'}, {affiliates=>'affiliates'} ],
group_by => [ 'me.id' ],
'+select' => [ {'count' => '*'}, 'table2.id' ],
'+as' => [ 'Count', 'ID' ],
});
当我尝试在 resultset 上执行 next 时,我得到异常“Not a ARRAY reference”。请注意,我不允许在DBIx :: Class中使用 join ,因为 referrers 和 affiliates 表,与* table没有任何关系***表。
如何让DBIx :: Class代码等同于SQL多选表?
答案 0 :(得分:4)
如果你没有table1 / 2和referrers / affiliates之间的关系,那么为什么不在你的DBIx :: Class结果类中创建它们呢?
你没有粘贴那些,所以我在这里猜测,你想在你的Table1类中添加这样的东西:
__PACKAGE__->has_many('affiliates', 'MyDB::Schema::Affiliate', 'loginid');
在表2中:
__PACKAGE__->has_many('referrers', 'MyDB::Schema::Referrer', 'loginid');
修正这些类名以匹配您的实际类。
我会猜测你使用Schema :: Loader加载你的表,并没有为你创建这些,因为你的数据库没有设置适当的外键? DBIx :: Class并不关心,您可以非常高兴地在其中设置更多关系,这些关系不是实际的FK,它将为您创建所需的连接。
HTH。
答案 1 :(得分:1)
我可以简单地创建一个视图来映射那些WHERE和FROM语句,而不是在DBIx中手工编写复杂查询。然后,只使用单行DBIx:
$bom_schema->resultset('View_Of_Table1_And_Table2_And_Referrers_And_Affiliates');