- substr $foreign_key_definition, $list_start, $list_end - $list_start, $sorted_foreign_keys;;
- }
+ # Split the whole chunk on double new lines. The resulting
+ # elements are one relationship each. Then fix the relationship
+ # names and sort them by their new names.
+ my @new_foreign_keys = sort map { fix_relationship_names($domain, $table, $_) } split m/\n\n/m, $1;
+
+ # Replace the function parameters = the actual relationship
+ # definitions with the new ones.
+ my $sorted_foreign_keys = "(\n" . join("\n\n", @new_foreign_keys) . "\n)";
+ substr $foreign_key_definition, $list_start, $list_end - $list_start, $sorted_foreign_keys;