2012-01-20 57 views
3

在我們的MySQL數據庫中,我有一個third_party_accounts表和has_manythird_party_campaigns。但是,並非所有帳戶都會有廣告系列。我想在DBIx::Class中做的只是選擇那些擁有一個或多個廣告系列的帳戶。最簡單的是,我發現如下:DBIx :: Class:只選擇has_many大於零的結果

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) 

這似乎是這樣一個明顯的使用案例,我敢肯定有一個簡單的方法這個,但我找不到它。

回答

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

這已經提示給我,但它不起作用。請注意,在我最初的查詢中,我有'group_by =>「me.id」'。這可以防止重複的ThirdPartyAccount記錄。這個「反向」解決方案,與我上面的數據一起,將給我留下*兩個* ThirdPartyAccount'對象,其ID爲1. – Ovid

+1

爲避免重複返回,將'{distinct => 1}'添加到' - > search_related '電話。 – ilmari