| 1 | package ObjectDB::Meta::Relationship::ManyToMany; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use base 'ObjectDB::Meta::Relationship'; | ||
| 7 | |||
| 8 | our $VERSION = '3.26'; | ||
| 9 | |||
| 10 | use ObjectDB::Util qw(load_class); | ||
| 11 | |||
| 12 | sub new { | ||
| 13 | my $self = shift->SUPER::new(@_); | ||
| 14 | my (%params) = @_; | ||
| 15 | |||
| 16 | $self->{map_class} = $params{map_class}; | ||
| 17 | $self->{map_from} = $params{map_from}; | ||
| 18 | $self->{map_to} = $params{map_to}; | ||
| 19 | |||
| 20 | return $self; | ||
| 21 | } | ||
| 22 | |||
| 23 | sub type { 'many to many' } | ||
| 24 | sub is_multi { 1 } | ||
| 25 | |||
| 26 | sub map_to { $_[0]->{map_to} } | ||
| 27 | sub map_from { $_[0]->{map_from} } | ||
| 28 | |||
| 29 | sub map_class { | ||
| 30 | my $self = shift; | ||
| 31 | |||
| 32 | my $map_class = $self->{map_class}; | ||
| 33 | |||
| 34 | load_class $map_class; | ||
| 35 | |||
| 36 | return $map_class; | ||
| 37 | } | ||
| 38 | |||
| 39 | sub class { | ||
| 40 | my $self = shift; | ||
| 41 | |||
| 42 | return $self->{class} if $self->{class}; | ||
| 43 | |||
| 44 | $self->{class} = | ||
| 45 | $self->map_class->meta->get_relationship($self->{map_to})->class; | ||
| 46 | |||
| 47 | return $self->{class}; | ||
| 48 | } | ||
| 49 | |||
| 50 | sub to_source { | ||
| 51 | my $self = shift; | ||
| 52 | my (%options) = @_; | ||
| 53 | |||
| 54 | my ($map_from, $map_to) = | ||
| 55 | %{ $self->map_class->meta->get_relationship($self->{map_from})->map }; | ||
| 56 | my ($rel_from, $rel_to) = | ||
| 57 | %{ $self->map_class->meta->get_relationship($self->{map_to})->map }; | ||
| 58 | |||
| 59 | my $orig_table = $self->orig_class->meta->table; | ||
| 60 | my $map_table = $self->map_class->meta->table; | ||
| 61 | my $rel_table = $self->class->meta->table; | ||
| 62 | |||
| 63 | my @columns; | ||
| 64 | if ($options{columns}) { | ||
| 65 | $options{columns} = [ $options{columns} ] | ||
| 66 | unless ref $options{columns} eq 'ARRAY'; | ||
| 67 | @columns = @{ $options{columns} }; | ||
| 68 | unshift @columns, $self->class->meta->get_primary_key; | ||
| 69 | } | ||
| 70 | else { | ||
| 71 | @columns = $self->class->meta->get_columns; | ||
| 72 | } | ||
| 73 | |||
| 74 | my $name = $self->name; | ||
| 75 | |||
| 76 | return { | ||
| 77 | table => $map_table, | ||
| 78 | as => $map_table, | ||
| 79 | join => 'left', | ||
| 80 | constraint => [ "$orig_table.$map_to" => { -col => "$map_table.$map_from" } ] | ||
| 81 | }, | ||
| 82 | { | ||
| 83 | table => $rel_table, | ||
| 84 | as => $name, | ||
| 85 | join => 'left', | ||
| 86 | constraint => [ "$map_table.$rel_from" => { -col => "$name.$rel_to" } ], | ||
| 87 | columns => [@columns] | ||
| 88 | }; | ||
| 89 | } | ||
| 90 | |||
| 91 | 1; |