我正在使用DBIx::class作为Perl项目的或映射程序。在生成测试数据时,我使用DBIx::Class::ResultSet::new在内存中创建新实体。为了将实体与关系链接起来,我使用set_from_related。在我尝试设置has_many关系的值之前,这绝对是完美无瑕的。伪示例:
# 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
在DBIx::Class::Relationship::Base文档中找不到合适的方法。最接近我需要的是add_to_$rel,但是这个方法创建(持久化(实体。这对我来说不是一个选项,因为我的项目中使用的一些实体不属于我(没有写权限(。
有人知道如何在内存中为has_many关系添加实体吗?
这是不可能的,因为新创建的结果对象在持久化到数据库之前不会填充其主键列。您可能想要的是在事务中使用multi-create并运行它。