small cleanup to last patch
[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         use base qw/DBIx::Class/;
19
20         __PACKAGE__->load_components(qw/PK::Auto::SQLite Core DB/);
21         __PACKAGE__->connection(...);
22
23         # Set up a class for the 'authors' table
24         package MyApp::DBIC::Author;
25         use base qw/MyApp::DBIC/;
26
27         __PACKAGE__->table('authors');
28         __PACKAGE__->add_columns(qw/authID first_name last_name/);
29         __PACKAGE__->set_primary_key(qw/authID/);
30
31         # Define relationship to the link table
32         __PACKAGE__->has_many('b2a' => 'MyApp::DBIC::Book2Author', 'authID');
33
34         # Create the accessor for books from the ::Author class
35         sub books {
36           my ($self) = @_;
37           return MyApp::DBIC::Book->search(
38                 { 'b2a.authID' => $self->authID }, # WHERE clause
39                 { join => 'b2a' } # join condition (part of search attrs)
40             # 'b2a' refers to the relationship named earlier in the Author class.
41                 # 'b2a.authID' refers to the authID column of the b2a relationship,
42                 # which becomes accessible in the search by being joined.  
43           );
44         }
45
46         # define the link table class
47         package MyApp::DBIC::Book2Author;
48         use base qw/MyApp::DBIC/;
49
50         __PACKAGE__->table('book2author');
51         __PACKAGE__->add_columns(qw/bookID authID/);
52         __PACKAGE__->set_primary_key(qw/bookID authID/);
53
54         __PACKAGE__->belongs_to('authID' => 'MyApp::DBIC::Author');
55         __PACKAGE__->belongs_to('bookID' => 'MyApp::DBIC::Book');
56
57         package MyApp::DBIC::Book;
58         use base qw/MyApp::DBIC/;
59
60         __PACKAGE__->table('books');
61         __PACKAGE__->add_columns(qw/bookID title edition isbn publisher year/);
62         __PACKAGE__->set_primary_key(qw/bookID/);
63         
64         __PACKAGE__->has_many('b2a' => 'MyApp::DBIC::Book2Author', 'bookID');
65
66         sub authors {
67          my ($self) = @_;
68          return MyApp::DBIC::Author->search(
69            { 'b2a.bookID' => $self->bookID }, # WHERE clause
70            { join => 'b2a' }); # join condition (part of search attrs)
71         }
72
73         # So the above search returns an author record where the bookID field of the
74         # book2author table equals the bookID of the books (using the bookID 
75         # relationship table
76
77 =item Advanced Exception handling
78
79 =item Transactions
80
81 =back