docs patch from dopplecoder with cleanups to Cookbook example
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Manual / Cookbook.pod
CommitLineData
3b44ccc6 1=head1 NAME
9c82c181 2
3b44ccc6 3DBIx::Class::Manual::Cookbook - Misc receipes
ee38fa40 4
5=over 4
6
7=item Input validation.
8
9=item Using joins
10
11=item Many-to-many relationships
12
13This is not as easy as it could be, but it's possible. Here's an example to
14illustrate:
15
dfeba824 16 # Set up inherited connection information
17 package MyApp::DBIC;
ee38fa40 18
dfeba824 19 use base qw/DBIx::Class/;
ee38fa40 20
dfeba824 21 __PACKAGE__->load_components(qw/PK::Auto::SQLite Core DB/);
22 __PACKAGE__->connection(...);
ee38fa40 23
dfeba824 24 # Set up a class for the 'authors' table
25 package MyApp::DBIC::Author;
26 use base qw/MyApp::DBIC/;
ee38fa40 27
dfeba824 28 __PACKAGE__->table('authors');
29 __PACKAGE__->add_columns(qw/authID first_name last_name/);
30 __PACKAGE__->set_primary_key(qw/authID/);
ee38fa40 31
dfeba824 32 # Define relationship to the link table
33 __PACKAGE__->has_many('b2a' => 'MyApp::DBIC::Book2Author', 'authID');
ee38fa40 34
dfeba824 35 # Create the accessor for books from the ::Author class
36 sub books {
37 my ($self) = @_;
38 return MyApp::DBIC::Book->search(
39 { 'b2a.authID' => $self->authID }, { join => 'b2a' }
40 );
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.
44 }
ee38fa40 45
dfeba824 46 # define the link table class
47 package MyApp::DBIC::Book2Author;
ee38fa40 48
dfeba824 49 use base qw/MyApp::DBIC/;
ee38fa40 50
dfeba824 51 __PACKAGE__->table('book2author');
52 __PACKAGE__->add_columns(qw/bookID authID/);
53 __PACKAGE__->set_primary_key(qw/bookID authID/);
ee38fa40 54
dfeba824 55 __PACKAGE__->belongs_to('authID' => 'MyApp::DBIC::Author');
56 __PACKAGE__->belongs_to('bookID' => 'MyApp::DBIC::Book');
ee38fa40 57
dfeba824 58 package MyApp::DBIC::Book;
ee38fa40 59
dfeba824 60 use base qw/MyApp::DBIC/;
ee38fa40 61
dfeba824 62 __PACKAGE__->table('books');
63 __PACKAGE__->add_columns(qw/bookID title edition isbn publisher year/);
64 __PACKAGE__->set_primary_key(qw/bookID/);
65
66 __PACKAGE__->has_many('b2a' => 'MyApp::DBIC::Book2Author', 'bookID');
ee38fa40 67
dfeba824 68 sub authors {
69 my ($self) = @_;
70 return MyApp::DBIC::Author->search(
71 { 'b2a.bookID' => $self->bookID }, # WHERE clause
72 { join => 'b2a' }); # Join condition
73 }
74
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
77 # relationship table
ee38fa40 78
79=item Advanced Exception handling
80
81=item Transactions
82
83=back