7 package Music::Artist; 8 use base 'Music::DBI'; 9 Music::Artist->table('artist'); 10 Music::Artist->columns(All => qw/artistid name/); 11 Music::Artist->has_many(cds => 'Music::CD'); 12 13 package Music::CD; 14 use base 'Music::DBI'; 15 Music::CD->table('cd'); 16 Music::CD->columns(All => qw/cdid artist title/); 17 Music::CD->has_many(tracks => 'Music::Track'); 18 Music::CD->has_a(artist => 'Music::Artist'); 19 20 package Music::Track; 21 use base 'Music::DBI'; 22 Music::Track->table('track'); 23 Music::Track->columns(All => qw/trackid cd title/); 24 25 my $artist = Music::Artist->insert({ name => 'U2' }); 26 27 my $cd = $artist->add_to_cds({ 28 title => 'October', 29 }); 30 31 $cd->update;
Ejecución:
lhp@nereida:~/Lperl/src/CLASS_DBI$ perl synopsis1.pl lhp@nereida:~/Lperl/src/CLASS_DBI$ sqlite3 example.db SQLite version 3.3.8 Enter ".help" for instructions sqlite> .dump BEGIN TRANSACTION; CREATE TABLE artist ( artistid INTEGER PRIMARY KEY, name TEXT NOT NULL ); INSERT INTO "artist" VALUES(1, 'Michael Jackson'); INSERT INTO "artist" VALUES(2, 'Eminem'); INSERT INTO "artist" VALUES(3, 'U2'); CREATE TABLE cd ( cdid INTEGER PRIMARY KEY, artist INTEGER NOT NULL REFERENCES artist(artistid), title TEXT NOT NULL ); INSERT INTO "cd" VALUES(1, 1, 'Thriller'); INSERT INTO "cd" VALUES(2, 1, 'Bad'); INSERT INTO "cd" VALUES(3, 2, 'The Marshall Mathers LP'); INSERT INTO "cd" VALUES(4, 3, 'October'); CREATE TABLE track ( trackid INTEGER PRIMARY KEY, cd INTEGER NOT NULL REFERENCES cd(cdid), title TEXT NOT NULL ); INSERT INTO "track" VALUES(1, 3, 'The Way I Am'); INSERT INTO "track" VALUES(2, 3, 'Stan'); INSERT INTO "track" VALUES(3, 1, 'Billie Jean'); INSERT INTO "track" VALUES(4, 2, 'Leave Me Alone'); INSERT INTO "track" VALUES(5, 2, 'Smooth Criminal'); INSERT INTO "track" VALUES(6, 1, 'Beat It'); INSERT INTO "track" VALUES(7, 2, 'Dirty Diana'); COMMIT; sqlite>
lhp@nereida:~/Lperl/src/CLASS_DBI$ cat -n synopsis2.pl 1 #!/usr/local/bin/perl -w .. .............................. # like in the former example 25 26 my $cd = Music::Artist->search_like(name => 'Eminem')->first; 27 28 print $cd->artistid,": ",$cd->name,"\n"; 29 30 my $first = Music::Artist->retrieve(1); 31 print $first->name,"\n"; 32 33 print "CDs\n"; 34 for my $cd (Music::CD->retrieve_all) { 35 print "\t",$cd->title,"\n"; 36 }
lhp@nereida:~/Lperl/src/CLASS_DBI$ perl synopsis2.pl 2: Eminem Michael Jackson CDs Thriller Bad The Marshall Mathers LP
Casiano Rodríguez León