gorm 多对多问题

gorm many to many proplem

我有 3 个 table 已经存在,现在我想建立关系,但我所做的一切都是空的 问题类别为空 有接口table字段(app_products_playlist_category): ID playlist_id category_id

我认为问题出在外键上,但我不知道如何为现有的 table 设置它。

type PlayListModel struct {
    gorm.Model
    Id             int             `gorm:"column:id" json:"id"`
    Published      string          `gorm:"column:published" json:"published"`
    Type_PlayLIST1 string          `gorm:"column:type_playlist1" json:"type_playlist1"`
    Type_PlayLIST2 string          `gorm:"column:type_playlist2" json:"type_playlist2"`
    Type_PlayLIST3 string          `gorm:"column:type_playlist3" json:"type_playlist3"`
    Type_PlayLIST4 string          `gorm:"column:type_playlist4" json:"type_playlist4"`
    Price          int             `gorm:"column:price"  json:"price"`
    Price_Orginal  int             `gorm:"column:price_orginal" json:"price_orginal"`
    Main_img       string          `gorm:"column:main_img" json:"main_img"`
    UserId         int             `gorm:"column:user_id"`
    LIkesCount     string          `gorm:"column:likes_count" json:"likes_count"`
    ViewsCount     string          `gorm:"column:views_count" json:"views_count"`
    Content        string          `gorm:"column:content"  json:"content"`
    Title          string          `gorm:"column:title" json:"title"`
    Categories     []CategoryModel `gorm:"many2many:app_products_playlist_category;foreignKey:ID;references:ID"`
}

func (playlist *PlayListModel) TableName() string {
    return "app_products_playlist"
}
func GetPlayList(playlist *[]PlayListModel, order string) {
    Db.Order(order).Find(&playlist)
}
package models

import "gorm.io/gorm"

type CategoryModel struct {
    gorm.Model
    Id       string          `grom:column:"id" json:"id"`
    Name     string          `grom:column:"name" json:"name"`
    Img      string          `grom:column:"img" json:"img"`
    Slug     string          `grom:column:"slug" json:"slug"`
    Row      string          `grom:column:"row" json:"row"`
    ParenID  string          `grom:column:"parent_id" json:"parent_id"`
    PlayList []PlayListModel `gorm:"many2many:app_products_playlist_category"`
}

func (category *CategoryModel) TableName() string {
    return "app_category_category"
}
package models

import "gorm.io/gorm"

type PlayListCategoryModel struct {
    PlayListID int `gorm:"primary_key;column:playlist_id" json:"playlist_id"`
    CategoryID int `gorm:"primary_key;column:category_id" json:"category_id"`
    PlayListModel
    CategoryModel
}

func (PlayListCategoryModel) TableName() string {
    return "app_products_playlist_category"
}

func (PlayListCategoryModel) BeforeCreate(db *gorm.DB) error {
    err := db.SetupJoinTable(&PlayListModel{}, "Categories", &PlayListCategoryModel{})
    return err
}






-- auto-generated definition
create table app_products_playlist
(
    id             serial
        primary key,
    published      varchar(10),
    title          varchar(255),
    type_playlist1 varchar(255),
    type_playlist2 varchar(255),
    price          integer,
    price_orginal  integer,
    main_img       varchar(100)             not null,
    created_at     timestamp with time zone not null,
    user_id        integer
        constraint app_products_playlist_user_id_9fb269b5_fk_app_account_user_id
            references app_account_user
            deferrable initially deferred,
    likes_count    integer,
    type_playlist3 varchar(50),
    views_count    integer,
    content        text,
    type_playlist4 varchar(50),
    deleted_at     timestamp with time zone
);

alter table app_products_playlist
    owner to honardari;

create index app_products_playlist_user_id_9fb269b5
    on app_products_playlist (user_id);

-- auto-generated definition
create table app_category_category
(
    id        serial
        primary key,
    name      varchar(255),
    important varchar(5),
    img       varchar(100),
    pub_date  date,
    slug      varchar(50),
    row       integer not null,
    lft       integer not null
        constraint app_category_category_lft_check
            check (lft >= 0),
    rght      integer not null
        constraint app_category_category_rght_check
            check (rght >= 0),
    tree_id   integer not null
        constraint app_category_category_tree_id_check
            check (tree_id >= 0),
    level     integer not null
        constraint app_category_category_level_check
            check (level >= 0),
    parent_id integer
        constraint app_category_categor_parent_id_0984d0d6_fk_app_categ
            references app_category_category
            deferrable initially deferred
);

alter table app_category_category
    owner to honardari;

create index app_category_category_slug_6027a7e5
    on app_category_category (slug);

create index app_category_category_slug_6027a7e5_like
    on app_category_category (slug varchar_pattern_ops);

create index app_category_category_tree_id_35de0819
    on app_category_category (tree_id);

create index app_category_category_parent_id_0984d0d6
    on app_category_category (parent_id);


-- auto-generated definition
create table app_products_playlist_category
(
    id          serial
        primary key,
    playlist_id integer not null
        constraint app_products_playlis_playlist_id_f13be1da_fk_app_produ
            references app_products_playlist
            deferrable initially deferred,
    category_id integer not null
        constraint app_products_playlis_category_id_d6c7fd45_fk_app_categ
            references app_category_category
            deferrable initially deferred,
    constraint app_products_playlist_ca_playlist_id_category_id_88f46dfa_uniq
        unique (playlist_id, category_id)
);

alter table app_products_playlist_category
    owner to honardari;

create index app_products_playlist_category_playlist_id_f13be1da
    on app_products_playlist_category (playlist_id);

create index app_products_playlist_category_category_id_d6c7fd45
    on app_products_playlist_category (category_id);



[{"ID":0,"CreatedAt":"2021-12-28T19:15:38.761224+03:30","UpdatedAt":"0001-01-01T00:00:00Z","DeletedAt":null,"id":9,"published":"2","type_playlist1":"","type_playlist2":"","type_playlist3":"2","type_playlist4":"2","price":0,"price_orginal":1000,"main_img":"playlist/reza/download.jfif","UserId":2,"likes_count":"","views_count":"","content":"تست تست تست تست تستست تستست تستست","title":"آموزش کیف چرم","Categories":null},{"ID":0,"CreatedAt":"2022-01-03T15:13:11.485185+03:30","UpdatedAt":"0001-01-01T00:00:00Z","DeletedAt":null,"id":10,"published":"2","type_playlist1":"","type_playlist2":"","type_playlist3":"2","type_playlist4":"2","price":0,"price_orginal":2500,"main_img":"playlist/09301292813/QYfe8BCL.1.jpg","UserId":1,"likes_count":"","views_count":"","content":"سشدیندشسیسشsss ssdasd","title":"آموزش کیف چرم 2","Categories":null}]

标题

假设您已经用 categories 创建了一个 playlistModel,像这样:

db.Create(&PlayListModel{
        Published: time.Now().String(),
        Categories: []CategoryModel{
            {Name: "test-category"},
        },
    })

查询returns里面的playlistModel和categories,需要用到Preload方法,这样:

var playlist []*PlayListModel
    db.Preload("Categories").Find(&playlist)

添加:

;joinForeignKey:playlist_id;joinReferences:category_id

Categories     []CategoryModel 

如下所示:

type PlayListModel struct {
    gorm.Model
    Id             int             `gorm:"column:id" json:"id"`
    Published      string          `gorm:"column:published" json:"published"`
    Type_PlayLIST1 string          `gorm:"column:type_playlist1" json:"type_playlist1"`
    Type_PlayLIST2 string          `gorm:"column:type_playlist2" json:"type_playlist2"`
    Type_PlayLIST3 string          `gorm:"column:type_playlist3" json:"type_playlist3"`
    Type_PlayLIST4 string          `gorm:"column:type_playlist4" json:"type_playlist4"`
    Price          int             `gorm:"column:price"  json:"price"`
    Price_Orginal  int             `gorm:"column:price_orginal" json:"price_orginal"`
    Main_img       string          `gorm:"column:main_img" json:"main_img"`
    UserId         int             `gorm:"column:user_id"`
    LIkesCount     string          `gorm:"column:likes_count" json:"likes_count"`
    ViewsCount     string          `gorm:"column:views_count" json:"views_count"`
    Content        string          `gorm:"column:content"  json:"content"`
    Title          string          `gorm:"column:title" json:"title"`
Categories     []CategoryModel `gorm:"many2many:app_products_playlist_category;joinForeignKey:playlist_id;joinReferences:category_id"`
}