Reputation: 10981
I have two tables: Region
and District
. So region_id
is the foreign key
into the table District
(a region
has one or many districts
). So, when I select a region
on my list
I only want to display the districts
associated with that particular region
.
My correct code displays all the districts
independently of region
:
def list = {
params.max = Math.min(params.max? params.int('max') : 20, 100)
[districtInstanceList : District.list(params),
districtInstanceTotal: District.count()]
}
Does someone know how to only display based on the foreign key constraint? I know I could write a SQL
query in my list
closure, but I suppose grails probably has a way to do it.
My database is MySQL
, and the grails
version is 2.0.1
.
My District
domain is:
class District {
def scaffold = true
String name
String description
String logo
String homepage
// defines the 1:n constrain with the Region table
static belongsTo = [region : Region]
// defines the 1: constraint with the Stream table
static hasMany = [streams : Stream]
static constraints ={
name(blank:false, minSize:6, maxSize:30)
description(blank: false, maxSize:100)
}
public String toString(){
name
}
}
Upvotes: 2
Views: 1085
Reputation: 35951
You can use GORM:
def list = {
params.max = Math.min(params.max? params.int('max') : 20, 100)
Region region = Region.get(params.id) // or what parameter you're using
List districts = District.findAllByRegion(region)
[districtInstanceList : districts,
districtInstanceTotal: District.count()]
}
You can read about Grails GORM here: http://grails.org/doc/latest/guide/GORM.html
Upvotes: 4