package MySchema::CD;
use Moose;
use MooseX::DBIC;
has_column title => ( is => 'ro', isa => 'Str' );
belongs_to artist => ( is => 'ro', isa => 'MySchema::Artist' );
package MySchema::Artist;
use Moose;
use MooseX::DBIC;
has_column name => ( is => 'ro', isa => 'Str' );;
has_many cds => ( is => 'ro', isa => 'MySchema::CD' );
package MySchema;
use Moose;
extends 'MooseX::DBIC::Schema';
__PACKAGE__->load_namespaces();
package main;
my $schema = MySchema->connect( 'dbi:SQLite::memory:' );
$schema->deploy;
my $artist = $schema->resultset('Artist')->create(
{
name => 'Mo',
cds => [ { title => 'Sound of Moose' } ],
}
);
my @artists = $schema->resultset('Artist')
->order_by('name')
->prefetch('cds')
->all;- Convention over Configuration
- Mandatory Single Primary Key
-
By default, all result classes have a primary key attribute, named
id. For maximum portability, a random string is genereated instead of using an incrementing integer. - Single Column Primary Key Tables Only
-
Primary keys consisting of more than one column are not (yet) supported.
package MySchema::Artist;
use MooseX::DBIC;
# column and relationship definition
__PACKAGE__->meta->make_immutable; # speed- table
-
table 'mytable';Specifying a table name is optional. By default MooseX::DBIC will use the package name as table name. Given the name of the schema is
MySchema, a result classMySchema::Artistwill lead to a table namedartist. - has_column
-
has_column 'name'; use MooseX::Types::Email qw(EmailAddress); has_column email => ( is => 'ro', isa => EmailAddress );Add a column to the result class. See MooseX::DBIC::Meta::Role::Column for further details.
- remove
-
remove 'id'; has_column mypk => ( primary_key => 1, auto_increment => 1, isa => 'Int' );Remove a previously added column. Can be used to remove the default primary key column
id. - has_many
-
has_many cds => ( is => 'ro', isa => 'MyApp::CD' ); - belongs_to
-
belongs_to producer => ( is => 'ro', isa => 'MyApp::Producer' ); - might_have
-
might_have artwork => ( is => 'ro', isa => 'MyApp::Artwork' ); - has_one
-
has_one mandatory_artwork => ( is => 'ro', isa => 'MyApp::Artwork' ); - with
-
with 'AutoUpdate'; with 'MooseX::DBIC::Role::AutoUpdate'; # same as aboveThis is the preferred way to apply roles to the class. with has been overridden to allow for a shorter syntax.
See the
MooseX::DBIC::Role::namespace for more roles.
One of the big advantages that come with Moose is the ability to introspect classes, attributes and pretty much everything. MooseX::DBIC adds methods to the meta class to get easy access to columns, relationships and more.
my $meta = MyApp::Artist->meta;Check out MooseX::DBIC::Meta::Role::Class to get started.