我发现的解决方案也不是很好,但它确实有效。如果我有时间,我可能会将这段代码合并到一个 CPAN 模块中,让它更漂亮一些。
package ParentSchema::Result::Class;
use strict;
use warnings;
use parent 'DBIx::Class::Core';
__PACKAGE__->add_columns(
"user_id",
{
data_type => "integer",
size => 32,
is_foreign_key => 1,
is_auto_increment => 0,
is_nullable => 0,
default_value => '',
},
);
# stuff common to all schemas
__PACKAGE__->belongs_to(
"user",
"Schema::Result::User",
{ 'foreign.id' => "self.user_id" },
{ is_deferrable => 1, on_delete => "CASCADE", on_update => "CASCADE" },
);
1;
package Schema::Result::Class::Author
use strict;
use warnings;
use parent 'ParentSchema::Class';
__PACKAGE__->table('class_author');
# class spesific stuff
__PACKAGE__->meta->make_immutable;
1;
package Schema::Result::User;
use strict;
use warnings;
use parent 'DBIx::Class::Core';
use Module::Pluggable::Object;
use String::CamelCase qw(decamelize);
__PACKAGE__->add_columns(
"id",
{
data_type => "integer",
size => 32,
is_auto_increment => 1,
is_nullable => 0,
default_value => '',
},
);
my $class_path = 'Schema::Result::Class';
my $mp = Module::Pluggable::Object->new(
search_path => [ $class_path ]
);
my @class_plugins = $mp->plugins;
foreach my $class (@class_plugins) {
(my $name = $class) =~ s/^\Q${class_path}\E//;
__PACKAGE__->might_have(
decamelize($name),
$class,
{ "foreign.user_id" => "self.id" },
{ cascade_copy => 0, cascade_delete => 0 },
);
}
__PACKAGE__->meta->make_immutable;
1;