如何在Grails 3中创建3个域关系?

时间:2015-11-20 15:46:47

标签: grails gorm grails-3.0

我有3个域类,我需要定义他们的关系,但我发现没有正确定义它们的运气。有人可以纠正我的代码吗?我总是得到指向id的错误未知列。请帮忙。以下是我的代码。谢谢。

Todo.groovy课程

package todoScaff

import userScaff.User
import categoryScaff.Category

class Todo {

String name
String note
Date createDate
Date dueDate
Date completedDate
String priority
String status
User owner
Category category

static belongsTo = [User, Category]

static constraints = {
    name(blank:false)
    createDate()
    priority()
    status()
    note(maxsize:1000, nullable:true)
    completedDate(nullable:true)
    dueDate(nullable:true)
}


 String toString() {
    name
 }


}

Category.groovy class

package categoryScaff

import todoScaff.Todo
import userScaff.User

class Category {

String name
String description
User user
static belongsTo = User
static hasMany = [todos: Todo]


static constraints = {
    name(blank:false)
}

 String toString(){
    name
 }

}

User.groovy class

package userScaff

import todoScaff.Todo
import categoryScaff.Category

class User {

String userName
String fname
String lname

static hasMany = [todos: Todo, categories: Category]

static constraints = {

    userName(blank:false, unique:true)
    fname(blank:false)
    lname(blank:false)
}

 String toString(){
    "$lname, $fname"
 }

}

错误

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

我很确定你的SQL表是不正确的。

我用3个域类创建了一个小项目,并使用了grails命令schema-export;删除与域关系无关的所有内容后,结构应如下所示:

create table category (
    id bigint,
    user_id bigint,
);
create table todo (
    id bigint,
    category_id bigint,
    owner_id bigint,
);
create table user (
    id bigint
);

如果您的表结构与此类似,则应更改它以匹配或使用域类中的static mapping = {}闭包来指示正确的列名。

静态制图
Todo

static mapping = {
    owner column: 'owner_id' // change owner_id to match your owner column within todo
    category column: 'category_id' // change category_id to match your category column within todo
}

Category

static mapping = {
    owner user: 'user_id' // change user_id to match your user column within category
}