你熟悉DBIx::Class::Schema::Loader吗?虽然它可以在一次性脚本中用于在内存中动态创建 DBIC 模式,但它也能够以“一次性”模式运行,在这种模式下,它将模式定义写入磁盘供您编辑和构建,它比你想象的要先进得多。
首先,您希望架构实际存在于数据库中,以便加载程序可以扫描它。然后你做类似的事情:
perl -MDBIx::Class::Schema::Loader=make_schema_at \
-e 'make_schema_at("MyApp::Schema", {dump_directory=>"schema_out"},' \
-e '["dbi:DBType:connstring", "user", "pass"]);'
(其中“MyApp::Schema”是您希望生成的模式类共享的包名称,“schema_out”是您希望在其中生成它们的目录)。
在此之后,您可以编辑生成的模式类,或者,如果您发现加载器做得足够好(或者至少做得足够好,您不需要编辑“不要在上面编辑”这条线”行),您可以决定数据库中的模式是您的主要来源,并保存 Schema::Loader 脚本以再次运行以在数据库更改时自动重新生成类。
更新
使用 DBIx::Class::Schema::Loader v0.05002 无法正确处理上述模式的部分内容,因为思南设法找到了一个错误!如果“引用”部分和列名不在同一行,则无法正确解析外键约束。
该错误已在 DBICSL git 中修复,但由于尚未发布修复程序,因此关系应该如下所示(我省略了列定义以节省空间;它们应该就像加载器当前生成它们一样)。
EventAttendee.pm
__PACKAGE__->set_primary_key(qw(event_id person_id));
__PACKAGE__->belongs_to(
"event" => "MyApp::Schema::Result::Event",
{ event_id => "event_id" },
{}
);
__PACKAGE__->belongs_to(
"person" => "MyApp::Schema::Result::Person",
{ person_id => "person_id" },
{}
);
事件.pm
__PACKAGE__->set_primary_key("event_id");
__PACKAGE__->belongs_to(
"event_creator" => "MyApp::Schema::Result::Person",
{ person_id => "event_creator" },
{ join_type => "LEFT" },
);
__PACKAGE__->has_many(
"event_attendees" => "MyApp::Schema::Result::EventAttendee",
{ "foreign.event_id" => "self.event_id" },
);
# Not auto-generated, but you probably want to add it :)
__PACKAGE__->many_to_many(
"people_attending" => "event_attendees" => "person"
);
人.pm
__PACKAGE__->has_many(
# It might be wise to change this to "events_created"
"events" => "MyApp::Schema::Result::Event",
{ "foreign.event_creator" => "self.person_id" },
);
__PACKAGE__->has_many(
"event_attendees" => "MyApp::Schema::Result::EventAttendee",
{ "foreign.person_id" => "self.person_id" },
);
# Not auto-generated, but you probably want to add it :)
__PACKAGE__->many_to_many(
"events_attending" => "event_attendees" => "event"
);