简体   繁体   English

Grails-[1:N]关系问题

[英]Grails - [1:N] Relationship issue

I have 2 different domain classes, one for Employee and one for Departments. 我有2种不同的域类,一种用于员工,一种用于部门。 The relationship between them is [1:N],which means that many employees can work at one Department but not vice versa. 他们之间的关系是[1:N],这意味着许多员工可以在一个部门工作,反之亦然。 The issue is that, after Grails creates the tables from the domain classes when the project runs, for one employee, the department Id of that table references the id on Department Table. 问题是,在项目运行时Grails从域类创建表之后,对于一名员工,该表的部门ID引​​用了Department Table上的ID。 For example, for a user named "Peter", department id would be 1. 例如,对于名为“ Peter”的用户,部门ID为1。

The department table also has names for the departments, along with the department id's. 部门表还具有部门的名称以及部门ID。

How can I reference the department_id in employee table to point at department.name instead of department.id ? 如何在员工表中引用department_id指向department.name而不是department.id?

Department Domain Class : 部门领域类别:

class Department {
    String name

    static hasMany = [
            employees: Employee
    ]

    static constraints = {
    }

    static mapping = {
        version false
    }

    def String toString() {
        name
    }


}

Employee Domain Class : 员工域类别:

class Employee {
    String firstName
    String lastName
    String email
    String country
    int born

    static belongsTo = [department: Department]

    static constraints = {
        firstName(blank: false)
        lastName(blank: false)
        born(blank: false)
        email(blank: false, email: true)
        country(blank: false)
    }

    static mapping = {
        version false
    }
}

What I need is, when in Employee table, the department_id column to reference at department.name instead of department.id. 我需要的是,在Employee表中时,要在department.name而不是department.id引用的department_id列。

I guess you need to configure that the Primary Key of the Department table is 'name' instead of the default 'id' column. 我猜您需要将Department表的主键配置为“名称”,而不是默认的“ id”列。 Grails will then use the name as the Foreign Key. 然后,Grails将使用该名称作为外键。

ie: 即:

class Department {
...
    static mapping = {
        id name: 'name'
    }
...
}

ref (Grails 3.1) : http://docs.grails.org/3.1.x/ref/Database%20Mapping/id.html ref(Grails 3.1): http : //docs.grails.org/3.1.x/ref/Database%20Mapping/id.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM