From 7b529ba46e03fbecc9fab009d9748e05abac049a Mon Sep 17 00:00:00 2001 From: ericprd Date: Mon, 17 Mar 2025 22:35:22 +0800 Subject: [PATCH] fix: add clicked count on ads --- internal/accessor/ads/get-all.go | 11 ++++++++--- internal/accessor/ads/impl.go | 2 +- internal/domain/ads/spec.go | 5 +++++ internal/services/ads/get_all.go | 2 +- internal/services/ads/impl.go | 2 +- 5 files changed, 16 insertions(+), 6 deletions(-) diff --git a/internal/accessor/ads/get-all.go b/internal/accessor/ads/get-all.go index fd02b1e..fe62a51 100644 --- a/internal/accessor/ads/get-all.go +++ b/internal/accessor/ads/get-all.go @@ -5,9 +5,14 @@ import ( adsdomain "legalgo-BE-go/internal/domain/ads" ) -func (a *accessor) GetAll() ([]adsdomain.Ads, error) { - var ads []adsdomain.Ads - if err := a.db.Find(&ads).Error; err != nil { +func (a *accessor) GetAll() ([]adsdomain.AdsResponse, error) { + var ads []adsdomain.AdsResponse + + if err := a.db.Table("ads"). + Select("ads.*, COUNT(log_ads.ads_id) as clicked"). + Joins("LEFT JOIN log_ads ON log_ads.ads_id = ads.id"). + Group("ads.id"). + Scan(&ads).Error; err != nil { return ads, fmt.Errorf("failed to get all ads: %v", err) } diff --git a/internal/accessor/ads/impl.go b/internal/accessor/ads/impl.go index 9125259..864ef11 100644 --- a/internal/accessor/ads/impl.go +++ b/internal/accessor/ads/impl.go @@ -11,7 +11,7 @@ type accessor struct { type Ads interface { Create(adsdomain.Ads) error - GetAll() ([]adsdomain.Ads, error) + GetAll() ([]adsdomain.AdsResponse, error) Update(adsdomain.Ads) error Delete(string) error } diff --git a/internal/domain/ads/spec.go b/internal/domain/ads/spec.go index 011f063..3e456d5 100644 --- a/internal/domain/ads/spec.go +++ b/internal/domain/ads/spec.go @@ -14,6 +14,11 @@ type Ads struct { UpdatedAt time.Time `json:"updated_at"` } +type AdsResponse struct { + Ads + Clicked int64 `json:"clicked"` +} + type AdsReq struct { Image string `json:"image" validate:"required"` URL string `json:"url" validate:"required"` diff --git a/internal/services/ads/get_all.go b/internal/services/ads/get_all.go index 2647303..3e2eefb 100644 --- a/internal/services/ads/get_all.go +++ b/internal/services/ads/get_all.go @@ -2,6 +2,6 @@ package adssvc import adsdomain "legalgo-BE-go/internal/domain/ads" -func (i *impl) GetAll() ([]adsdomain.Ads, error) { +func (i *impl) GetAll() ([]adsdomain.AdsResponse, error) { return i.adsRepo.GetAll() } diff --git a/internal/services/ads/impl.go b/internal/services/ads/impl.go index 0042992..a1c4fd1 100644 --- a/internal/services/ads/impl.go +++ b/internal/services/ads/impl.go @@ -11,7 +11,7 @@ type impl struct { type Ads interface { Create(adsdomain.AdsReq) error - GetAll() ([]adsdomain.Ads, error) + GetAll() ([]adsdomain.AdsResponse, error) Update(string, adsdomain.AdsReq) error Delete(string) error }