Files
jh-zz/actions/cities.go
2025-09-10 19:35:06 +08:00

56 lines
1.3 KiB
Go

package actions
import (
"fmt"
"zzman/model"
"gorm.io/gorm"
)
func FindCities(tx *gorm.DB) ([]model.City, error) {
var cities []model.City
if err := tx.Find(&cities, "label is not null").Error; err != nil {
return nil, fmt.Errorf("failed to find cities: %w", err)
}
return cities, nil
}
func FindCitiesWithEdgesCount(tx *gorm.DB) ([]model.City, error) {
var datas []struct {
model.City
EdgesCount int `gorm:"column:edges_count"`
}
err := tx.
Select("cityhash.*, COUNT(edge.id) AS edges_count").
Joins("LEFT JOIN edge ON edge.city_id = cityhash.id").
Where("cityhash.label IS NOT NULL").
Group("cityhash.id").
Find(&datas).Error
if err != nil {
return nil, fmt.Errorf("failed to find cities with edges count: %w", err)
}
var cities = make([]model.City, len(datas))
for i, data := range datas {
cities[i] = data.City
cities[i].EdgesCount = data.EdgesCount
}
return cities, nil
}
func UpdateCitiesOffset(tx *gorm.DB, updates []model.City) error {
if len(updates) == 0 {
return nil
}
for _, city := range updates {
err := tx.Model(new(model.City)).
Where("id = ?", city.Id).
Update("offset", city.Offset).Error
if err != nil {
return fmt.Errorf("failed to update city id %d offset: %w", city.Id, err)
}
}
return nil
}