In our MySQL database, I have a third_party_accounts
table and it has_many
third_party_campaigns
. However, not all accounts will have campaigns. What I would like to do in DBIx::Class
is select only those accounts which have one or more campaigns. The simplest was I've found is as follows:
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',
}
);
For the relevant database columns:
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)
This seems like such an obvious use case that I'm sure there's a simple way to do this, but I can't find it.
my $with_campaigns_rs =
$schema->resultset('ThirdPartyCampaigns')
->search_related('third_party_account');