如何通过DBIx为多对多关系插入数据?

时间:2013-11-08 11:13:41

标签: mysql sql perl orm dbix-class

我正试图了解DBiX,当我有多对多的关系时,我正在努力将数据插入到我的数据库中。

在下面的示例中,我在对象和网络之间存在多对多的关系。

对象具有名称和描述 网络具有IP和网络掩码

我有一个多对多关系的联结表。

如何添加对象及其关联网络?

例如我有

object
—————
Name : TestObject1
Description: TestObject1

使用以下网络

IP:1.1.1.1
Netmask:255.255.255.255

IP:2.2.2.2
Netmask:255.255.255.255

Name : TestObject2
Description: TestObject2

使用以下网络

IP:1.1.1.1
Netmask:255.255.255.255

IP:3.3.3.3
Netmask:255.255.255.255

我知道如何使用1到多个关系插入数据,但我无法弄清楚如何处理多对多。理想情况下,我希望能够构建我的数据结构,然后一次性添加它。

以下是由架构加载器创建的相关表。

感谢。

Object Table
------------

__PACKAGE__->table("Object");
__PACKAGE__->add_columns(
  "objectid",
  { data_type => "integer", is_auto_increment => 1, is_nullable => 0 },
  "description",
  { data_type => "varchar", is_nullable => 1, size => 100 },
  "objectname",
  { data_type => "varchar", is_nullable => 0, size => 100 },
);
__PACKAGE__->set_primary_key("objectid");

__PACKAGE__->has_many(
  "object_has_networks",
  "TestApp::Schema::Result::ObjectHasNetwork",
  { "foreign.object_objectid" => "self.objectid" },
  { cascade_copy => 0, cascade_delete => 0 },
);

__PACKAGE__->many_to_many(
  "network_networkids",
  "object_has_networks",
  "network_networkid",
);


 Network Table
 ------------

__PACKAGE__->table("network");
__PACKAGE__->add_columns(
  "networkid",
  { data_type => "integer", is_auto_increment => 1, is_nullable => 0 },
  “IP”,
  { data_type => "varchar", is_nullable => 1, size => 15 },
  "netmask",
  { data_type => "varchar", is_nullable => 1, size => 15 },
);
__PACKAGE__->set_primary_key("networkid");

__PACKAGE__->has_many(
  "object_has_networks",
  "TestApp::Schema::Result::ObjectHasNetwork",
  { "foreign.network_networkid" => "self.networkid" },
  { cascade_copy => 0, cascade_delete => 0 },
);
__PACKAGE__->many_to_many("object_objectids", "object_has_networks", "object_objectid");



Junction Table
--------------
__PACKAGE__->table("Object_has_network");
__PACKAGE__->add_columns(
  "object_objectid",
  { data_type => "integer", is_foreign_key => 1, is_nullable => 0 },
  "network_networkid",
  { data_type => "integer", is_foreign_key => 1, is_nullable => 0 },
);
__PACKAGE__->set_primary_key("object_objectid", "network_networkid");:wq
__PACKAGE__->belongs_to(
  "network_networkid",
  "TestApp::Schema::Result::Network",
  { networkid => "network_networkid" },
  { is_deferrable => 1, on_delete => "NO ACTION", on_update => "NO ACTION" },
);

__PACKAGE__->belongs_to(
  "object_objectid",
  "TestApp::Schema::Result::Object",
  { objectid => "object_objectid" },
  { is_deferrable => 1, on_delete => "NO ACTION", on_update => "NO ACTION" },
);

1 个答案:

答案 0 :(得分:2)

第一个DBIx是一个完整的命名空间,其中DBIx :: Class只是一个dist。常见的缩写是DBIC。

多对多不是一种关系,而是一种帮助,所以你只需要指定形成m2m关系桥的两个关系来进行搜索和插入。