我正在尝试构建一个我创建多对多的最小示例
DBIx::Class
中的关系,并在数据库中插入一些行。
在我的数据库中,我有两个表 A 和 C ,它们通过表 AC 链接。 我尝试使用以下脚本插入值:
#! /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);
创建值a1到a3和c1,c2就好了。当我尝试 将a1和c1之间的关系添加到表 AC 中。我收到以下错误消息:
Can't use an undefined value as a HASH reference at /Library/Perl/5.12/DBIx/Class/Relationship/ManyToMany.pm line 88.
我想我正在关注add_to_ $ rel的Documentation。我在这里做错了什么?
我使用以DBIx::Class::DeploymentHandler
部署到SQLite数据库中的以下数据库架构。
档案db/Main.pm
package DB::Main;
use base qw/DBIx::Class::Schema/;
our $VERSION = 1;
__PACKAGE__->load_namespaces;
1;
档案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;
档案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;
档案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;
答案 0 :(得分:3)
调用many_to_many的参数是错误的。请参阅many_to_many的文档并尝试以下操作:
__PACKAGE__->many_to_many('cs' => 'acs', 'c');
__PACKAGE__->many_to_many('as' => 'acs', 'a');