docs patch from dopplecoder with cleanups to Cookbook example
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Manual / Cookbook.pod
1 =head1 NAME 
2
3 DBIx::Class::Manual::Cookbook - Misc receipes
4
5 =over 4
6
7 =item Input validation.
8
9 =item Using joins
10
11 =item Many-to-many relationships
12
13 This is not as easy as it could be, but it's possible. Here's an example to 
14 illustrate:
15
16         # Set up inherited connection information
17         package MyApp::DBIC; 
18
19         use base qw/DBIx::Class/;
20
21         __PACKAGE__->load_components(qw/PK::Auto::SQLite Core DB/);
22         __PACKAGE__->connection(...);
23
24         # Set up a class for the 'authors' table
25         package MyApp::DBIC::Author;
26         use base qw/MyApp::DBIC/;
27
28         __PACKAGE__->table('authors');
29         __PACKAGE__->add_columns(qw/authID first_name last_name/);
30         __PACKAGE__->set_primary_key(qw/authID/);
31
32         # Define relationship to the link table
33         __PACKAGE__->has_many('b2a' => 'MyApp::DBIC::Book2Author', 'authID');
34
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         }
45
46         # define the link table class
47         package MyApp::DBIC::Book2Author;
48
49         use base qw/MyApp::DBIC/;
50
51         __PACKAGE__->table('book2author');
52         __PACKAGE__->add_columns(qw/bookID authID/);
53         __PACKAGE__->set_primary_key(qw/bookID authID/);
54
55         __PACKAGE__->belongs_to('authID' => 'MyApp::DBIC::Author');
56         __PACKAGE__->belongs_to('bookID' => 'MyApp::DBIC::Book');
57
58         package MyApp::DBIC::Book;
59
60         use base qw/MyApp::DBIC/;
61
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');
67
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
78
79 =item Advanced Exception handling
80
81 =item Transactions
82
83 =back