我有以下 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' ],
});
当我尝试对结果集执行 next 时,出现异常“Not an ARRAY reference”。请注意,我不允许在 DBIx::Class 中使用 join,因为引用表和附属表与 *table*** 表没有关系。
如何让 DBIx::Class 代码等效于 SQL 多选表?
最佳答案
如果 table1/2 和引用者/附属机构之间没有关系,那么为什么不在 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,它会为您创建所需的连接。
哈。
关于sql - 从 DBIx::Class 中的多个表中选择,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/784438/