DBIx :: Class:仅选择has_many大于零的结果

时间:2012-01-20 12:46:19

标签: mysql perl orm dbix-class

在我们的MySQL数据库中,我有一个third_party_accounts表,has_many third_party_campaigns。但是,并非所有帐户都有广告系列。我想在DBIx::Class中执行的操作是仅选择包含一个或多个广告系列的帐户。最简单的是我发现如下:

my $third_party_account_rs = $schema->resultset('ThirdPartyAccount');
my $with_campaigns_rs      = $third_party_account_rs->search(
    { third_party_account_id => \'IS NOT NULL' },
    {
        join     => 'third_party_campaigns',
        group_by => 'me.id',                                                                                                                                 
    }
);

对于相关的数据库列:

mysql> select id from third_party_accounts;
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
+----+
3 rows in set (0.00 sec)

mysql> select id, third_party_account_id from third_party_campaigns;
+----+------------------------+
| id | third_party_account_id |
+----+------------------------+
|  1 |                      1 |
|  2 |                      2 |
|  3 |                      1 |
+----+------------------------+
3 rows in set (0.00 sec)

这似乎是一个明显的用例,我确信有一个简单的方法可以做到这一点,但我找不到它。

1 个答案:

答案 0 :(得分:5)

my $with_campaigns_rs = 
    $schema->resultset('ThirdPartyCampaigns')
    ->search_related('third_party_account');