violates foreign key constraint (SQLSTATE 23503)

i face this error when trying to generate my comment attach to the topics:

fail to create comments, err=error while scanning created comment IDs, err=ERROR: insert or update on table “comments” violates foreign key constraint “comments_topic_id_fkey” (SQLSTATE 23503

this is my comment_dao.go

func (d CommentDAO) Create(comments ...dto.Comment) ([]dto.Comment, error) {
    if len(comments) == 0 {
        return nil, nil
    }
    
    query := d.genInsertSQL(len(comments))
    var args []any
    for _, c := range comments {
        args = append(args, c.By, c.TopicID, c.Content, time.Now())
    }
    
    res, err := d.db.Query(query, args...)
    if err != nil {
        return nil, fmt.Errorf("fail to create comments: %w", err)
    }
    
    ids := make([]int, 0, len(comments))
    for res.Next() {
        var id int
        if err = res.Scan(&id); err != nil {
            return nil, fmt.Errorf("fail to scan for created comment ID: %w", err)
        }
        ids = append(ids, id)
    }

    if err = res.Err(); err != nil {
        return nil, fmt.Errorf("error while scanning created comment IDs, err=%w", err)
    }

    for i, c := range comments {
        c.ID = ids[i]
    }

    return comments, nil
}

func (d CommentDAO) genInsertSQL(numComments int) string {
    var sb strings.Builder
    sb.WriteString(`insert into msg_board.comments(by, topic_id, content, created_at) values `)
    genSQLParams(numComments, &sb, 4)
    sb.WriteString(` returning id;`)
    return sb.String()
}

my seed.go to run generate

const numUsers = 10



func genTopics(db *sql.DB, users []dto.User) ([]dto.Topic, error) {
    const minTopic = 2
    const maxTopic = 5

    topics := make([]dto.Topic, 0, len(users)*minTopic)
    now := time.Now()

    for _, u := range users {
        n := randInt(minTopic, maxTopic)
        for i := 0; i < n; i++ {
            topics = append(topics, dto.Topic{
                By:    u.ID,
                Title: fmt.Sprintf("topic %d by user %d at %d", i+1, u.ID, now.Unix()),
                Body:  "random string at " + now.String(),
            })
        }
    }

    d := dao.NewTopicDAO(db)
    createdTopics, err := d.Create(topics...)
    if err != nil {
        return nil, err
    }

    if len(createdTopics) == 0 {
        return nil, fmt.Errorf("no topics created")
    }

    log.Printf("Created topics: %v", createdTopics)
    return createdTopics, nil
}



func genComments(db *sql.DB, users []dto.User, topics []dto.Topic) {
    const minComments = 1
    const maxComments = 5

    comments := make([]dto.Comment, 0, len(topics)*maxComments)
    now := time.Now()

    for _, topic := range topics {
        log.Printf("Creating comments for topic ID: %d", topic.ID)
        n := randInt(minComments, maxComments)
        for i := 0; i < n; i++ {
            user := users[rand.Intn(len(users))]
            comment := dto.Comment{
                By:        user.ID,
                TopicID:   topic.ID,
                Content:   fmt.Sprintf("Comment %d by user %d on topic %d", i+1, user.ID, topic.ID),
                CreatedAt: now,
            }
            comments = append(comments, comment)
        }
    }

    d := dao.NewCommentDAO(db)
    createdComments, err := d.Create(comments...)
    if err != nil {
        log.Printf("fail to create comments, err=%v", err)
    } else {
        log.Printf("created comments: %v", createdComments)
    }
}

func randInt(min, max int) int {
    return rand.Int()%(max-min) + min
}

this is my dto.go



type Topic struct {
    ID        int       json:"id,omitempty"
    CreatedAt time.Time json:"created_at"

    By           int    json:"by,omitempty"
    Title        string json:"title,omitempty"
    Body         string json:"body,omitempty"
    CommentCount int    json:"comment_count,omitempty"
    Upvotes      int    json:"upvotes,omitempty"
}

type Comment struct {
    ID        int       json:"id,omitempty"
    CreatedAt time.Time json:"created_at"

    By      int    json:"by,omitempty"
    Content string json:"content,omitempty"
    TopicID int    json:"topic_id,omitempty"
} ```   

 I have try to catching error logs, fix the dto but it not work

New contributor

NervX is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật