简体   繁体   English

构造DBIx :: Class对象和相关对象,但稍后保存

[英]Construct DBIx::Class object and related objects but save later

I would like to construct a DBIx::Class object and its related objects but defer saving the object, calling the insert method on the object later and at that time have everything saved all at once. 我想构造一个DBIx :: Class对象及其相关对象,但推迟保存该对象,稍后再在该对象上调用insert方法,这时可以一次保存所有内容。

Here is example code based on the examples from the DBIx::Class documentation (artist, cd, etc.). 这是基于DBIx :: Class文档(艺术家,CD等)中示例的示例代码。

use MyApp::Schema;
use Data::Dumper ;

sub make_artist_from_some_other_object
{
  my ($object, $schema) = @_ ; 

  my $artist = $schema->resultset('Artist')->new({});
  $artist->name($object->firstname() . ' ' . $object->lastname()) ;

  $artist->new_related('cds', {'title' => $object->firsttitle(), 
                               'year'  => $object->firstyear()}) ;
  $artist->new_related('cds', {'title' => $object->secondtitle(), 
                               'year'  => $object->secondyear()}) ;
  $artist->new_related('cds', {'title' => $object->thirdtitle(), 
                               'year'  => $object->thirdyear()}) ;
  return $artist ;
}

my $schema = MyApp::Schema->connect('dbi:SQLite:dbname=/tmp/abcd.sqlite');
$artist = make_artist_from_some_other_object($some_object, $schema) ;
$artist->insert() ;
# The insert does _not_ save cd information.

I realize there are ways around this, eg, keeping the related objects around and then saving them individually, but what I am looking for is a built-in DBIx::Class way to do all the object construction beforehand and then do a single insert sometime later. 我意识到有很多解决方法,例如保留相关对象然后分别保存,但是我要寻找的是内置的DBIx :: Class方式,可以预先完成所有对象的构造,然后进行一次插入一段时间之后。 Is this possible? 这可能吗?

There is currently no way to do that. 目前尚无办法。 You can only create separate objects with new_result and insert them later with insert. 您只能使用new_result创建单独的对象,并稍后使用insert插入它们。 Often the primary key(s) are assigned by the database so they aren't available before that. 通常,主键是由数据库分配的,因此在此之前它们不可用。 You can try to populate the relationship cache to achieve what you want. 您可以尝试填充关系缓存以实现所需的内容。 What's your reason to not immediately insert all rows? 您为何不立即插入所有行的原因是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM