I noticed you are calling a query from within a for loop. That’s very inefficient. Just execute a single query and pass all the samples you are iterating to be part of an IN clause.
More, it’s not clear why you are setting the sample association. Is it for the UI only? If you really need to set the FKs in the DB, just run a bulk update query.