Problem
I’m trying to build a minimal example where I create a many-to-many
relationship in DBIx::Class and insert some rows into the database.
In my database I have two tables A and C which are linked by the table AC.
I try to insert the values using the following script:
#! /usr/bin/perl
use strict;
use warnings;
use DB::Main;
my $s = DB::Main->connect("dbi:SQLite:example.db");
my $a1 = $s->resultset('A')->create({a_value => 'a1'});
my $a2 = $s->resultset('A')->create({a_value => 'a2'});
my $a3 = $s->resultset('A')->create({a_value => 'a3'});
$s->resultset('C')->create({c_value => 'c1'});
$s->resultset('C')->create({c_value => 'c2'});
my $c1 = $s->resultset('C')->find(1);
$c1->add_to_as($a1);
The values a1 to a3 and c1,c2 get created just fine. When I try to
add the relationship between a1 and c1 into the table AC. I get the following error message:
Can't use an undefined value as a HASH reference at /Library/Perl/5.12/DBIx/Class/Relationship/ManyToMany.pm line 88.
I think I am following the Documentation of add_to_$rel to the letter. What am I doing wrong here?
Schema Definition
I’m using the following database schema which I deploy with DBIx::Class::DeploymentHandler into an SQLite database.
File db/Main.pm
package DB::Main;
use base qw/DBIx::Class::Schema/;
our $VERSION = 1;
__PACKAGE__->load_namespaces;
1;
File db/Main/Result/A.pm
package DB::Main::Result::A;
use base qw/DBIx::Class::Core/;
__PACKAGE__->table('a');
__PACKAGE__->add_columns(
a_id => {
data_type => 'Integer',
size => 8
},
a_value => {
data_type => 'Varchar',
size => 50
},
);
__PACKAGE__->set_primary_key('a_id');
__PACKAGE__->has_many('acs' => 'DB::Main::Result::AC', 'f_a_id');
__PACKAGE__->many_to_many('cs' => 'DB::Main::Result::C', 'acs');
1;
File db/Main/Result/C.pm
package DB::Main::Result::C;
use base qw/DBIx::Class::Core/;
__PACKAGE__->table('c');
__PACKAGE__->add_columns(
c_id => {
data_type => 'Integer',
size => 8
},
c_value => {
data_type => 'Varchar',
size => 50
},
);
__PACKAGE__->set_primary_key('c_id');
__PACKAGE__->has_many('acs' => 'DB::Main::Result::AC', 'f_c_id');
__PACKAGE__->many_to_many('as' => 'DB::Main::Result::A', 'acs');
1;
File db/Main/Result/AC.pm
package DB::Main::Result::AC;
use base qw/DBIx::Class::Core/;
__PACKAGE__->table('ac');
__PACKAGE__->add_columns(
f_a_id => {
data_type => 'Integer',
size => 8
},
f_c_id => {
data_type => 'Integer',
size => 8
},
);
__PACKAGE__->set_primary_key('f_a_id', 'f_c_id');
__PACKAGE__->belongs_to('a' => 'DB::Main::Result::A', 'f_a_id');
__PACKAGE__->belongs_to('c' => 'DB::Main::Result::C', 'f_c_id');
1;
The arguments in your calls to many_to_many are wrong. Consult the documentation of many_to_many and try the following: