TigerTiger
TigerTiger

Reputation: 10806

How to save multiple rows of data by looping through an array or a map?

Class Buyer {
   String name
   static constraints = {
   }
}
Class Order {
    String ref
    static belongsTo = [buyer:Buyer]
    static constraints = {
    buyer(nullable:false)
    }
}

In OrderController.groovy

...
def someAction = {
  //working
  def data1 = ["buyer.id": 2, "ref": "xyz"]
  def ord = new Order(data1);
  ord.save();

  def data2 = ["buyer.id": 2, "ref": "234xyz"]
  def ord2 = new Order(data2);
  ord2.save();


  //But in a loop - its not working
  def items = ['abc', 'def', 'ghi', 'jkl']
  def data2 = [:]
  for(e in items) {
     data2 = ["buyer.id": 2, "ref" : e.value] //keeping buyer id same
     def ord = new Order(data2);
     ord.save();
     data2 = [:] //just emptying it?
  }
}

As you would notice in "working" above, if I am able to save multiple rows by copy pasting and definging new maps but If I try to loop through an array, it doesnt work. Any ideas how do I save data by looping through an array or a map?

Any questions, please let know Thanks

Upvotes: 0

Views: 2201

Answers (2)

tim_yates
tim_yates

Reputation: 171184

You should just be able to do:

def someAction = {
  def items = ['abc', 'def', 'ghi', 'jkl']
  items.each { item ->
     def ord = new Order( [ 'buyer.id':2, ref:item ] )
     ord.save()
  }
}

What errors (if any) are you getting?

Also, why are you doing e.value? This will get you an array of Character rather than a String (which is what your first working example is using)

Upvotes: 0

Hoàng Long
Hoàng Long

Reputation: 10848

First, I'm not sure about ["buyer.id": 2, "ref" : e.value], I think it should be [buyer: Buyer.get(2), ref : e.value].

Second, I would recommend using cascading save to do the task. You can try something like this(You need to define a static hasMany = [orders: Order] relation in Buyer for Buyer-Order relationship.

Buyer b = new Buyer(name: "foo")
for(e in items) {
     def ord = new Order(ref: e.value);
     b.addToOrders(ord)
  }

b.save(flush:true)

Upvotes: 2

Related Questions