3 DBIx::Class::Manual::Cookbook - Misc recipes
7 Things that could be handy
11 =item Input validation.
15 =item Many-to-many relationships
17 This is not as easy as it could be, but it's possible. Here's an example to
20 # Set up inherited connection information
22 use base qw/DBIx::Class/;
24 __PACKAGE__->load_components(qw/PK::Auto::SQLite Core DB/);
25 __PACKAGE__->connection(...);
27 # Set up a class for the 'authors' table
28 package MyApp::DBIC::Author;
29 use base qw/MyApp::DBIC/;
31 __PACKAGE__->table('authors');
32 __PACKAGE__->add_columns(qw/authID first_name last_name/);
33 __PACKAGE__->set_primary_key(qw/authID/);
35 # Define relationship to the link table
36 __PACKAGE__->has_many('b2a' => 'MyApp::DBIC::Book2Author', 'authID');
38 # Create the accessor for books from the ::Author class
41 return MyApp::DBIC::Book->search(
42 { 'b2a.authID' => $self->authID }, # WHERE clause
43 { join => 'b2a' } # join condition (part of search attrs)
44 # 'b2a' refers to the relationship named earlier in the Author class.
45 # 'b2a.authID' refers to the authID column of the b2a relationship,
46 # which becomes accessible in the search by being joined.
50 # define the link table class
51 package MyApp::DBIC::Book2Author;
52 use base qw/MyApp::DBIC/;
54 __PACKAGE__->table('book2author');
55 __PACKAGE__->add_columns(qw/bookID authID/);
56 __PACKAGE__->set_primary_key(qw/bookID authID/);
58 __PACKAGE__->belongs_to('authID' => 'MyApp::DBIC::Author');
59 __PACKAGE__->belongs_to('bookID' => 'MyApp::DBIC::Book');
61 package MyApp::DBIC::Book;
62 use base qw/MyApp::DBIC/;
64 __PACKAGE__->table('books');
65 __PACKAGE__->add_columns(qw/bookID title edition isbn publisher year/);
66 __PACKAGE__->set_primary_key(qw/bookID/);
68 __PACKAGE__->has_many('b2a' => 'MyApp::DBIC::Book2Author', 'bookID');
72 return MyApp::DBIC::Author->search(
73 { 'b2a.bookID' => $self->bookID }, # WHERE clause
74 { join => 'b2a' }); # join condition (part of search attrs)
77 # So the above search returns an author record where the bookID field of the
78 # book2author table equals the bookID of the books (using the bookID
81 =item Advanced Exception handling