I have 2 Lucid models: Ad
and Campaign
, which are associated using a Many:Many relationship. They have a pivot table which manages the relationship which has additional information, so my table structure is as follows:
- ads
- id
- ...
- campaign_ads
- campaign_id
- ad_id
- spend
- sent
- clicks
- leads
- ftds
- campaigns
- id
- ...
I am trying to fetch the results of a paginate
query using the Ad
models' query
function, but in addition to the Ad
models' fields, I would also like to fetch the sum of spend
, sent
, clicks
, leads
and ftds
from the related Campaign
models' pivots.
I have come up with the following code, which returns the correct information in the collection, but returns an incorrect value for the count
const Ad = use('App/Models/Ad');
const query = Ad.query()
.leftJoin('campaign_ads', 'ads.id', 'campaign_ads.ad_id')
.select('ads.*')
.sum('campaign_ads.spend as spend')
.sum('campaign_ads.sent as sent')
.sum('campaign_ads.clicks as clicks')
.sum('campaign_ads.leads as leads')
.sum('campaign_ads.ftds as ftds')
.groupBy('ads.id')
.paginate()
I assume that this is related to how the paginate
function rewrites or performs the query, but I have no idea how to fix it.