简体   繁体   中英

ActiveJdbc update join-table attribute

Good evening, I am trying to update a join-table attribute for existing records. I have two models, one called Records , the other called Shoppingcarts . These are connected by a join table called records_shoppingcarts . I added a relationship attribute to the join table called record_amount which is supposed to hold the amount of each record in the join table. At the moment, whenever an item is added to a shoppingcart, only one item is added. The user is then able to modify the amount of items in the shoppingcart in their checkout view. I am handling this by querying the join table records_shoppingcarts for entries with the corresponding record_id and updating the column record_amount to the new amount of records in the shoppingcart. This looks something linke that:

List<RecordsShoppingcarts> associations = RecordsShoppingcarts.where("shoppingcart_id = ?", s.get("id"));

            //update the number of records in the join table
            for(RecordsShoppingcarts rs : associations) {                    

                if((int)rs.getInteger("record_id") == (int)rec.getInteger("id")) {
                    rs.delete(); //cleanup
                    rs.set("record_amount", amount);
                    rs.saveIt();                        

                }
            }                
        }

Unfortunately though, whenever saveIt() gets called; the entry isn't updated in the database but a new entry is created with the same shoppingcart_id , recordId and the updated amount. I am probably missing something here, since I can't imagine manually updating join tables is intended. Unfortunately though, I couldn't find anything on updating relationship attributes in join tables. Is this even provided by ActiveJdbc?

Any help would be much appreciated. Best wishes, derelektrischemoench

The framework is working exactly as expected. You need to familiarize yourself with how it decides to create a new record or update an existing one by reading this page: http://javalite.io/surrogate_primary_keys

Basically, you are deleting a record by:

 rs.delete();

so, next time you do:

rs.saveIt();   

it creates a new record. Simply remove the rs.delete(); and you will be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM