+sub update_collection {
+ my ($self, $attribute, $entries) = @_;
+
+ my $self_primary_key = "" . ($self->meta->primary_key_columns)[0];
+
+ croak "\$self hasn't been saved yet" if !$self->$self_primary_key;
+
+ my $relationship = first { $_->name eq $attribute } @{ $self->meta->relationships };
+
+ croak "No relationship found for attribute '$attribute'" if !$relationship;
+
+ my @primary_key_columns = $relationship->class->meta->primary_key_columns;
+
+ croak "Classes with multiple primary key columns are not supported" if scalar(@primary_key_columns) > 1;
+
+ my $class = $relationship->class;
+ my $manager_class = "SL::DB::Manager::" . substr($class, 8);
+ my $other_primary_key = "" . $primary_key_columns[0];
+ my $column_map = $relationship->column_map;
+ my @new_entries = @{ $entries // [] };
+ my @existing_entries = @{ $self->$attribute // [] };
+ my @to_delete = grep { my $value = $_->$other_primary_key; !any { $_->{$other_primary_key} == $value } @new_entries } @existing_entries;
+
+ $_->delete for @to_delete;
+
+ foreach my $entry (@new_entries) {
+ if (!$entry->{$other_primary_key}) {
+ my $new_instance = $class->new(%{ $entry });
+
+ foreach my $self_attribute (keys %{ $column_map }) {
+ my $other_attribute = $column_map->{$self_attribute};
+ $new_instance->$other_attribute($self->$self_attribute);
+ }
+
+ $new_instance->save;
+
+ next;
+ }
+
+ my $existing = first { $_->$other_primary_key == $entry->{$other_primary_key} } @existing_entries;
+ $existing->update_attributes(%{ $entry }) if $existing;
+ }
+}
+