如何在范围内插入结构?
//Department array (department table)
var depValues []model.Department = []model.Department{
model.Department{DepartmentName: "Software Analyst", DeptCode: "SA"},
model.Department{DepartmentName: "Bussiness Analyst", DeptCode: "BA"},
}
for _, dep := range depValues {
db.Create(&dep) //It's working fine
}
在这里,dep.ID
返回两条记录id
//Another array (employee table)
var empValues []model.Employee = []model.Employee{
model.Employee{EmpId: "001", EmpName: "samsung", departmentRef: dep.ID},
model.Employee{EmpId: "002", EmpName: "Nokia", departmentRef: dep.ID},
}
现在,我想将departmentId
插入employee
表中,我该怎么做,任何人都可以教我。
已经尝试
它将返回重复值
var depValues []model.Department = []model.Department{
model.Department{DepartmentName: "Software Analyst", DeptCode: "SA"},
model.Department{DepartmentName: "Bussiness Analyst", DeptCode: "BA"},
}
for _, dep := range depValues {
db.Create(&dep)
//Insert into Employee
var empValues []model.Employee = []model.Employee{
model.Employee{EmpId: "001", EmpName: "samsung", DepRefer: dep.ID},
model.Employee{EmpId: "002", EmpName: "Nokia", DepRefer: dep.ID},
}
for _, empv := range empValues {
db.Create(&empv)
}
}
数据库重复记录
'1', '2018-07-10 15:12:27', '2018-07-10 15:12:27', NULL, '001', 'samsung', '1'
'2', '2018-07-10 15:12:28', '2018-07-10 15:12:28', NULL, '002', 'Nokia', '2'
'3', '2018-07-10 15:12:29', '2018-07-10 15:12:29', NULL, '001', 'samsung', '1'
'4', '2018-07-10 15:12:29', '2018-07-10 15:12:29', NULL, '002', 'Nokia', '2'
答案 0 :(得分:1)
如果我正确理解了您的问题,您有两个变量,并且它们都是切片。您想将其中一个附加到另一个变量:
这是您的代码和结果:
func main() {
var depValues = []Department{
{DepartmentName: "Software Analyst", DeptCode: "SA"},
{DepartmentName: "Bussiness Analyst", DeptCode: "BA"},
}
for _, dep := range depValues {
fmt.Println(dep)
var empValues = []Employee{
{EmpId: "001", EmpName: "samsung", DepRefer: 1},
{EmpId: "002", EmpName: "Nokia", DepRefer: 2},
}
for _, empv := range empValues {
fmt.Println(empv)
}
}
}
您的结果
{Software Analyst SA []}
{001 samsung 1}
{002 Nokia 2}
{Bussiness Analyst BA []}
{001 samsung 1}
{002 Nokia 2}
这是我的代码和结果
type Department struct {
DepartmentName string
DeptCode string
Employee []Employee
}
type Employee struct {
EmpId string
EmpName string
DepRefer int
}
func main() {
var depValues = []Department{
{DepartmentName: "Software Analyst", DeptCode: "SA"},
{DepartmentName: "Bussiness Analyst", DeptCode: "BA"},
}
var empValues = []Employee{
{EmpId: "001", EmpName: "samsung", DepRefer: 1},
{EmpId: "002", EmpName: "Nokia", DepRefer: 2},
}
for _, dep := range depValues {
dep.Employee = empValues
fmt.Println(dep)
}
}
和结果:
{Software Analyst SA [{001 samsung 1} {002 Nokia 2}]}
{Bussiness Analyst BA [{001 samsung 1} {002 Nokia 2}]}