Without using database I would like to construct a new DBIx::Class object (song) and attach a few multi-to-multi related objects (tag) to it. Then I would like to access tags in this way:
my @tags = $song->tags();
I already can do this if I first insert objects into database, but how to do this without using insert()?
Below is my code which outputs name of created tag. Now I would like to achieve this without using insert.
This is just test code. Otherwise I have a more complex schema that is used with MySql. Now I also use Solr and I want to convert Solr response to DBIx::Class objects (without accessing db).
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
package MySchema::Song;
use base 'DBIx::Class';
__PACKAGE__->load_components('Core');
__PACKAGE__->table("artist");
__PACKAGE__->add_columns(
id => { data_type => 'integer', is_nullable => 0, is_auto_increment => 1 },
name => { data_type => 'varchar', is_nullable => 1, },
);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->has_many('song_tag' => 'MySchema::SongTag', 'song_id');
__PACKAGE__->many_to_many('tags' => 'song_tag', 'tag');
package MySchema::Tag;
use base 'DBIx::Class';
__PACKAGE__->load_components('Core');
__PACKAGE__->table("tag");
__PACKAGE__->add_columns(
id => { data_type => 'integer', is_nullable => 0, is_auto_increment => 1 },
name => { data_type => 'varchar', is_nullable => 1, },
);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->has_many('song_tag' => 'MySchema::SongTag', 'tag_id');
__PACKAGE__->many_to_many('songs' => 'song_tag', 'song');
package MySchema::SongTag;
use base 'DBIx::Class';
__PACKAGE__->load_components('Core');
__PACKAGE__->table("song_tag");
__PACKAGE__->add_columns(
song_id => { data_type => 'integer', is_nullable => 0 },
tag_id => { data_type => 'integer', is_nullable => 0 },
);
__PACKAGE__->set_primary_key( qw(song_id tag_id) );
__PACKAGE__->belongs_to('song' => 'MySchema::Song','song_id');
__PACKAGE__->belongs_to('tag' => 'MySchema::Tag', 'tag_id');
package MySchema;
use base 'DBIx::Class::Schema';
__PACKAGE__->load_classes(qw(Song Tag SongTag));
package main;
my $schema;
$schema = MySchema->connect('dbi:SQLite:dbname=:memory:');
$schema->deploy;
my $song = $schema->resultset('Song')->new_result({ id => 1, name => 'Song name' });
my $tag = $schema->resultset('Tag')->new_result({ id => 1, name => 'Tag name' });
my $song_tag = $schema->resultset('SongTag')->new({
song => $song,
tag => $tag,
});
$song->add_to_tags($tag);
#$tag->add_to_songs($song); # one or another
$song->insert;
$tag->insert;
# This works if objects are previously inserted
foreach my $tag ($song->tags) {
print $tag->name."\n";
}
1;