Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use addTo with hasmany grails domain

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.

like image 763
akash777.sharma Avatar asked May 08 '14 08:05

akash777.sharma


1 Answers

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.

like image 145
Visme Avatar answered Nov 24 '22 17:11

Visme