fbfdedb3ed
ent 的 Update().Where() 对复合主键表会报 "sql/sqlgraph: invalid composite id for update table",这是 ent 框架已知的限制(field.ID 复合主键仅对 edge schema 完整支持)。同表的 Create/Delete/Query 操作不受影响,仅 Update 需要绕过。在 ServiceContext 中暴露底层 *sql.DB 以供 ExecContext 执行原生 SQL。
61 lines
1.6 KiB
Go
61 lines
1.6 KiB
Go
package logic
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"juwan-backend/app/shop/rpc/internal/svc"
|
|
"juwan-backend/app/shop/rpc/pb"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type UpdateShopPlayersLogic struct {
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
logx.Logger
|
|
}
|
|
|
|
func NewUpdateShopPlayersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateShopPlayersLogic {
|
|
return &UpdateShopPlayersLogic{
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
Logger: logx.WithContext(ctx),
|
|
}
|
|
}
|
|
|
|
func (l *UpdateShopPlayersLogic) UpdateShopPlayers(in *pb.UpdateShopPlayersReq) (*pb.UpdateShopPlayersResp, error) {
|
|
if in.ShopId <= 0 || in.PlayerId <= 0 {
|
|
return nil, errors.New("invalid shop_id or player_id")
|
|
}
|
|
|
|
// ent 的 Update().Where() 不支持复合主键表(shop_players 的主键是 (shop_id, player_id)),
|
|
// 会报 "sql/sqlgraph: invalid composite id for update table"。
|
|
// Create/Delete/Query 不受影响,仅 Update 需要走原生 SQL。
|
|
query := `UPDATE shop_players SET is_primary = $1, left_at = $2 WHERE shop_id = $3 AND player_id = $4`
|
|
|
|
var leftAt *time.Time
|
|
if in.LeftAt > 0 {
|
|
t := time.Unix(in.LeftAt, 0)
|
|
leftAt = &t
|
|
}
|
|
|
|
result, err := l.svcCtx.DBRW.ExecContext(l.ctx, query, in.IsPrimary, leftAt, in.ShopId, in.PlayerId)
|
|
if err != nil {
|
|
logx.Errorf("update shop players failed, %s", err.Error())
|
|
return nil, errors.New("update shop players failed")
|
|
}
|
|
|
|
affected, err := result.RowsAffected()
|
|
if err != nil {
|
|
logx.Errorf("get rows affected failed, %s", err.Error())
|
|
return nil, errors.New("update shop players failed")
|
|
}
|
|
if affected == 0 {
|
|
return nil, errors.New("shop player not found")
|
|
}
|
|
|
|
return &pb.UpdateShopPlayersResp{}, nil
|
|
}
|