Kriz Dee
Kriz Dee

Reputation: 25

DbiX::Class / Creating tree of test data without persisting

I'm using DBIx::Class as or mapper for my Perl project. When it comes to generating test data I'm using DBIx::Class::ResultSet::new to create new entities in memory. In order to link entities with relationships I use set_from_related. This works absolutely flawless until I try to set the value(s) for a has_many relationship. Pseudo example:

# Table 'AUTHOR' has 
#   one-to-one  (belongs_to) relationship named 'country' to table 'COUNTRY'
#   one-to-many (has_many) relationship named 'books' to table 'BOOK'
my $s       = Schema::getSchema();
my $author  = $s->resultset('Author')->new({ name => 'Jon Doe', year_of_birth => 1982 });
my $country = $s->resultset('Country')->new({ name => 'Germany', iso_3166_code => 'DE' }); 
my $book    = $s->resultset('Book')->new({ title => 'A star far away', publishing_year => 2002 });

# Now let's make 'em known to each other
$author->set_from_related('country', $country);
$author->set_from_related('books',   $book);

# At this point
#   $author->country      is defined
#   $author->books->first is undef    <<<---- Problem

I cannot find a suitable method in the DBIx::Class::Relationship::Base documentation. The one closest to what I need is add_to_$rel but this method creates (persists) the entities. This is not an option for me as some of the entites used in my project don't belong to me (no write permission).

Does anyone have an idea how to add entities in memory for a has_many relationship ?

Upvotes: 2

Views: 76

Answers (1)

Alexander Hartmaier
Alexander Hartmaier

Reputation: 2204

That's not possible as newly created result objects don't have their primary key column(s) populated until they are persisted to the database. What you possibly want is to use multi-create and run that inside a transaction.

Upvotes: 1

Related Questions