package My::ClassDBI; use strict; use warnings; use base 'Class::DBI'; # Here we create our 'main' connection # to the database my $dsn = 'dbi:mysql:database'; my $user = 'user'; my $password = 'password'; My::ClassDBI->set_db('Main', $dsn, $user, $password); # there is a one to one relationship # between a package and a table in the database # we will create 2 packages, one for the 'user' # table and one for the 'page' table # We upper case the table names our based on # accepted naming conventions for packages # but you could use any case. package Table::User; use base 'My::ClassDBI'; # tell Class::DBI which table with 'class' # is working with Table::User->table('user'); # important side note - # the All creation method only works correctly if the FIRST field # in the table is a primary, use the Primary assignment method # outlined in the docs if this is the case Table::User->columns(All => qw/user_id user_name first_name last_name password email city state postal_code phone_number address created_on modified_on/ ); 1; package Table::Page; use base 'My::ClassDBI'; Table::Page->table('page'); Table::Page->columns(All => qw/page_id user_id name filename created_on modified_on/ ); 1; # Now we assign a relationship # These become one of the most compelling reasons to invest # in learning and using a module like Class::DBI # Please read the Class::DBI docs for more information # on how relationships are managed # this statement tells Class::DBI that the 'user' table # has records that relate to it in the 'page' table # and that the *key* that relates them is the 'user_id' # field. The *key* has to be an index (or key depending # on SQL engine) in order for this relation to work. Table::User->has_many( 'pages' , 'Table::Page' => 'user_id' ); 1;