i have the following (simplified) domain classes
class Filter {
String name
static hasMany = [answers:Answer]
static belongsTo = [user:User]
}
class User {
String name
static hasMany = [answers:Answer, filters:Filter]
}
class Answer {
String text
}
Then i add answers to the user which is working perfectly. The problem occurs when i delete 1 answer of a user:
def delete = {
def answer = Answer.get(params.id)
def users = User.withCriteria() {
answers{
eq("id", answer.id)
}
}
for (user in users)
user.removeFromAnswers(answer)
answer.delete(flush:true)
redirect(action:"index")
}
What happens here is that ALL user --> answer associations get deleted.
I only want to delete this 1 answer and of cause all associations the answer is used.
I know this has to do with the missing belongsTo, but i can't use it because a ansswer can either belong to a user or to an filter...
You can add the belongsTo to set them to nullable:
class Answer {
String text
static belongsTo = [user:User, filter:Filter]
static constraints = {
user nullable:true
filter nullable:true
}
}
and then just delete the Answer directly in the Controller:
def delete = {
def answer = Answer.get(params.id)
answer.delete(flush:true)
}
GORM will take care of the rest the cascading for you.
Related
I'm new to Grails. I'm having problem with retrieving data from DB. I have domains with classes, something like...
class Lightbox {
String name = ''
String link = ''
static hasMany = [users: LightboxUserAccount]
}
class LightboxUserAccount {
UserAccount userAccount
static belongsTo = [lightbox: Lightbox]
}
class UserAccount {
String username
...
}
I want to list all "Lightboxes" owned by user with ID=4. I was trying
def my_lb = Lightbox.findAll("from Lightbox as lb where lb.users=:userAccount", [userAccount: springSecurityService.getCurrentUser()])
or
def my_lb = Lightbox.findAllByUsers(4)
None of those work for me. What am I doing wrong? Thx
Try this one:
Lightbox.findAll("from Lightbox as lb where :userAccount in (lb.users)", [userAccount: springSecurityService.getCurrentUser()])
So I did it slightly different, using criteria instead. Take a look if interested
static getAllByUserAccount(UserAccount userAccount) {
def criteria = Lightbox.createCriteria()
def my_lb = criteria.list {
users {
eq('userAccount', userAccount)
}
}
return my_lb
}
It seems to be working. Thanks for responses though
Assuming I have a Person and a Status. If Status is like this :
class Status {
String text
Person author
}
I would have done something like this to get the messages list of the current user :
def messages = Status.withCriteria {
author {
eq 'username', currentPerson.username
}
}
But if my relationship in Status is like this, how can I do so?
static belongsTo = [Person]
Thanks for your help.
I tend to use the map notation for belongsTo, so I would do it like this:
class Status {
String text
static belongsTo = [author: Person]
}
Then you're query is easy:
def messages = Status.findAllByAuthor(currentPerson)
If you had bidirectional added into Person with hasMany:
class Person {
static hasMany = [messages: Status]
}
You could also do this:
def messages = currentPerson.messages
I read that a m:m relationship often means there is a third class that isn't yet required. So I have m:m on User and Project, and I created a third domain class, ProjectMembership
The three domains are as follows (minimized for illustration purposes):
User
class User {
String name
static hasMany = [projectMemberships : ProjectMembership]
}
Project Membership
class ProjectMembership {
static constraints = {
}
static belongsTo = [user:User, project:Project]
}
Project:
class Project {
String name
static hasMany = [projectMemberships : ProjectMembership]
static constraints = {
}
}
If I have the ID of the user, how can I get a list of Project objects that they are assigned to?
There are a handful of ways - here are a couple:
def user = User.get(userId)
ProjectMembership.findAllByUser(user).collect { it.project }
or to avoid the query for the User:
ProjectMembership.withCriteria {
user {
eq('id', userId)
}
}.collect { it.project }
Be wary of queries that'll return large result sets - you'll end up with a huge in-memory list of project objects.
I have a relationship between two domain class: User and Bank, user has many of bank and bank has many of user, the result table I call it as mm_user_banks that keep both table IDs for MM relationship.
class User {
String name
String password
Date createdAt = new Date()
Date loginAt
static hasMany = [banks:Bank]
static fetchMode = [banks: 'eager']
static constraints = {
}
static mapping = {
banks joinTable: [name: 'mm_user_banks', key: 'mm_user_id']
}
}
and Bank...
class Bank {
Long id
String name
static belongsTo = User
static hasMany = [users:User]
static constraints = {
}
static mapping = {
id generator: 'assigned'
users joinTable: [name: 'mm_user_banks', key: 'mm_bank_id'], lazy: false
}
}
I can save users with banks as well, but the problem is when I try to retrieve bank list from an user instance and it only fetch one row even if there is more than one row for this user in mm_user_banks table.
E.g:
User u = new User(name: 'user', password: 'pwd')
u.addToBanks(Bank.findById(1))
u.addToBanks(Bank.findById(2))
u.addToBanks(Bank.findById(3))
u.save(flush: true)
In database it is OK, fetching 3 rows, but when I get the user and see its bank list:
def user = User.findById(1) //OK
println "Size ${user.banks?.size()}" //only 1??? How?
Thanks in advance!
Just tested it out - "user.banks?.size()" returns "3". Are you sure that data in DB is OK?
Anyway, if you want to use eager fetching for collections then define it in "mapping" of User class (instead of "fetchMode" static field):
static mapping = {
banks joinTable: [name: 'mm_user_banks', key: 'mm_user_id'], fetch: 'join'
}
in Bank class use fetch: 'join' in mapping instead of lazy: false
Thanks so much, Sergei, but didn't worked out.
I fixed it in an ugly way, but this is was my remaining way out.
I created another domain class to mapping the MM table, so I did a mm_user_banks class. I use it to fetch records from bank or user and worked OK. To save banks for a user I actually do it in the old way as well, not changed from that. I guess this mighty not be the best way, but like I said, worked out.
I've tried "fetch: 'join'" and "lazy: false" and "static fetchMode = [banks: 'eager']" without success.
The new domain class is:
class UserBanks {
User user
Bank bank
static constraints = {
}
static mapping = {
table name: 'mm_user_banks'
user column: 'mm_user_id'
bank column: 'mm_bank_id'
}
}
I had the similar problem but in my case I had another relation between my equivalents to User and the Bank. This made the hasMany statement to use the wrong relation to map the many to many relation. In my case it was solved by adding a mappedBy statement to the relation:
class Bank{
...
static mappedBy=[users:'banks']
...
}
and
class User{
...
static mappedBy=[banks:'users']
...
}
or as it was in my case, since it was a uni-directional relation:
class ArticleGroup {
String name
static hasMany = [articles:Article]
static mappedBy = [articles: 'none']
static constraints = {
name(nullable:false, blank:false, unique:true, maxSize:100)
}
static mapping = {
table 'article_group'
sort 'name'
articles joinTable: [name:'article_group_article', key: 'articleGroup_id', column:'article_id'], fetch: 'join'
}
I use grails-1.3.2 and hbase plugin.
I have some difficulty in creating one-to-Many association with
hbase (i can work with hibernate), so
i decided to try create one-to-Many association with using ArrayList.
Here are my domain classes and controllers:
class Contacts {
String con
static constraints = {}
}
class ContactsController {
def create = {
def contact = new Contacts()
contact.con = params.con
contact.save(flush:true)
}
}
class User {
String firstname
String lastname
// static hasMany = [contact: Contacts]
static ArrayList<Contacts> contact
static constraints = {}
}
class UserController{
def create = {
def user = new User()
user.properties = params
user.save(flush: true)
}
def addContact = {
def user = User.get(params.userID)
def contact = Contacts.get(params.contactID)
user.contact.add(contact)
user.save(flush:true)
}
}
In addContact action user.contact = null, so it can not work.
In user does nor appear contact field.
Can someone help me understand what i have to do for saving ArrayList in db?
I don't know anything about hbase, but the static contact property of the User class looks very suspicious. The fact that this property is static, implies that every user has the same contact list, which seems unlikely to be the desired behaviour.
In a standard GORM domain model - assuming you want each User to have their own contact list - this would be defined
class User {
String firstname
String lastname
static hasMany = [contact: Contacts]
}
Although it looks like we're also defining a static property here, it's actually just the definition of how the Contact and User classes are related (AKA mapping) that is static. The contact property that is dynamically added to the User class is non-static.
Aside
I recommend renaming the Contacts class to Contact and the contact property to contacts. The GORM mapping would then look like this:
class User {
String firstname
String lastname
static hasMany = [contacts: Contact]
}