Unable to use addTo with hasmany grails domain
Asked Answered
S

1

5

I have 2 tables in grails with mysql

say A and B

The scenarios that I want to implement here are :

(1)instance of A can have zero / one / more than one instance of B.

(2)when instance A is deleted then all its related Bs must be deleted.

(3)each instance of B must be associated with only one instance of A.

(4)A knows about B , but B does not know about A.

condition number 4 is not mandatory.

From the above info it seems like : unidirectional one to many from A to B

Currently what I am doing is: (taking help from here )

class A
{
  String name
  Set bs=[]
  static hasMany=[bs:B]
}

Class B
{
  String name
}

B b=new B(name:'bname')
b.save()
A a=new A(name:'aname')
a.addToBs(b)
a.save()

While saving both entries,(B is saving but A is not saving) I am using addTo and getting error no signature of the method addToBs()

Please help me and also correct me if I am wrong somewhere.

Synthesis answered 8/5, 2014 at 8:27 Comment(0)
H
8
class A
{
  String name
  static hasMany=[bs:B] //by default bs are Set. no need of explicit declaration
}

Class B
{
  String name
  static belongsTo = A //when delete a it's b also will get deleted
}

    B b1=new B(name:'bname1')
    B b2=new B(name:'bname11')
    B b3=new B(name:'bname2')
    A a=new A(name:'aname1')
    A a2=new A(name:'aname2')
    a.save(flush:true)
    a2.save(flush:true)
    a.addToBs(b1)
    a.addToBs(b2)
    a2.addToBs(b3)
    a.save(flush:true)
    a2.save(flush:true)

No need of save the instance of b. When we add the b instance into the collection of b's on a, it will automatically save the instance of b when we save the instance of a.

Hodess answered 8/5, 2014 at 8:46 Comment(3)
what if you don't have the belongsto relationship? i'm having a similar problem where if i save A after adding it to the hasmany list the list doesn't get updated. i can't have a belongsto because my class B could beelong to 2 different classes and i don't want those 2 classes to be linked in any way (ie: inheritence)Derwent
@Derwent You can always use interface, which both of these classes implement, and which will be an owner of these classes (they belongs to implementations of this interface).Mechelle
Is it absolutely necessary to perform flush for b's to be added to a?Shulamite

© 2022 - 2024 — McMap. All rights reserved.