gorm多对多问题

huangapple go评论74阅读模式
英文:

gorm many to many proplem

问题

我有3个已经存在的表,现在我想建立它们之间的关系,但是我所做的一切都返回为空。问题可能是类别为空。接口表字段如下(app_products_playlist_category):

id
playlist_id
category_id

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

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
}
-- 自动生成的定义
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);

-- 自动生成的定义
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);


-- 自动生成的定义
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 }]

英文:

I have 3 tables that already exist, now I want to relation , but everything I do comes back empty
proplem category is null
There are interface table fields (app_products_playlist_category):
id
playlist_id
category_id

I think the problem is with foregin key, but I do not know how to set it for existing tables.

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}]

Heading

gorm多对多问题
gorm多对多问题
gorm多对多问题

答案1

得分: 1

假设你已经创建了一个带有categoriesplaylistModel,就像这样:

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

要执行一个查询,返回包含playlistModel和其中的categories的结果,你需要使用Preload方法,像这样:

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

Supposing that you've created a playlistModel with categories, like this:

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

For do a query that returns playlistModel and categories inside, you need use Preload method, in this way:

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

答案2

得分: 0

将以下内容翻译为中文:

将以下内容添加到Categories []CategoryModel中:

;joinForeignKey:playlist_id;joinReferences:category_id

如下所示:

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"`
}
英文:

Add:

;joinForeignKey:playlist_id;joinReferences:category_id

to

Categories     []CategoryModel 

As done in the following:

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"`
}

huangapple
  • 本文由 发表于 2022年1月4日 21:52:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/70579831.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定