3 DBIx::Class::Manual::Cookbook - Misc receipes
7 =item Input validation.
11 =item Many-to-many relationships
13 This is not as easy as it could be, but it's possible. Here's an example to
16 # Set up inherited connection information
19 use base qw/DBIx::Class/;
21 __PACKAGE__->load_components(qw/PK::Auto::SQLite Core DB/);
22 __PACKAGE__->connection(...);
24 # Set up a class for the 'authors' table
25 package MyApp::DBIC::Author;
26 use base qw/MyApp::DBIC/;
28 __PACKAGE__->table('authors');
29 __PACKAGE__->add_columns(qw/authID first_name last_name/);
30 __PACKAGE__->set_primary_key(qw/authID/);
32 # Define relationship to the link table
33 __PACKAGE__->has_many('b2a' => 'MyApp::DBIC::Book2Author', 'authID');
35 # Create the accessor for books from the ::Author class
38 return MyApp::DBIC::Book->search(
39 { 'b2a.authID' => $self->authID }, { join => 'b2a' }
41 # 'b2a' refers to the relationship named earlier in the Author class.
42 # 'b2a.authID' refers to the authID column of the b2a relationship,
43 # which becomes accessible in the search by being joined.
46 # define the link table class
47 package MyApp::DBIC::Book2Author;
49 use base qw/MyApp::DBIC/;
51 __PACKAGE__->table('book2author');
52 __PACKAGE__->add_columns(qw/bookID authID/);
53 __PACKAGE__->set_primary_key(qw/bookID authID/);
55 __PACKAGE__->belongs_to('authID' => 'MyApp::DBIC::Author');
56 __PACKAGE__->belongs_to('bookID' => 'MyApp::DBIC::Book');
58 package MyApp::DBIC::Book;
60 use base qw/MyApp::DBIC/;
62 __PACKAGE__->table('books');
63 __PACKAGE__->add_columns(qw/bookID title edition isbn publisher year/);
64 __PACKAGE__->set_primary_key(qw/bookID/);
66 __PACKAGE__->has_many('b2a' => 'MyApp::DBIC::Book2Author', 'bookID');
70 return MyApp::DBIC::Author->search(
71 { 'b2a.bookID' => $self->bookID }, # WHERE clause
72 { join => 'b2a' }); # Join condition
75 # So the above search returns an author record where the bookID field of the
76 # book2author table equals the bookID of the books (using the bookID
79 =item Advanced Exception handling