2012-08-15 75 views
2

當您在DBIx::Class中有一個行對象時,您可以將相關對象作爲值傳遞給如何在DBIx :: Class中創建包含相關對象的行對象?

my $author = $authors_rs->find(1); 
my $book = $books_rs->create({ author => $author, title => 'title' }); 

但是,如果您以後使用author訪問器,則會從數據庫中再次檢索該對象。是否可以創建一個對象,以便在沒有附加查詢的情況下訪問關聯的對象?

+1

這是一個很好的問題。您可能想在DBIx :: Class郵件列表上詢問它,開發者在這裏列出。在我看來,創作之後緩存作者對象在書的範圍內應該是可能的。但是,DBIC可能總是偏向於檢索相關記錄以確保新鮮度。 – 2012-08-15 20:04:39

+0

發佈到DBIx :: Class郵件列表:http://lists.scsys.co.uk/pipermail/dbix-class/2012-August/010741.html – 2012-08-16 08:33:50

+0

今天早上看到了。 – 2012-08-16 14:35:20

回答

0

如何從$ author拷貝你想要的東西到一些普通的舊Perl變量中?

如果你想複製整個結構,clone模塊可能會有幫助(我沒有這個模塊的經驗,我剛剛在線找到它)。

0

我不確定我是否正確理解你,但如果我是,也許你想查看prefetch功能來自動準備好調用那些其他相關的行對象。

例如,在Galileo中,當列出所有頁面(文章)時,我使用此機制爲每個頁面對象(see here)獲取相關作者對象。


好吧,如果要將一個對象存儲在另一個對象中,您可能需要向對象中注入一些額外的數據。

UNTESTED:

## some initial checks (run these only once) 

# check that method name is available 
die "Cannot use method 'extra_data'" if $book->can('extra_data'); 

# check that the reftype is a hash 
require Scalar::Util; 
die "Incorrect underlying type" unless Scalar::Util::reftype($book) eq 'HASH'; 

# check that the key is available 
die "Key unavailable" if exists $book->{'my_extra_data'}; 

{ 
    no strict 'refs'; 
    # create a simple accessor for a hash stored in an object 
    *{ ref($book) . '::extra_data' } = sub { 
    my $self = shift; 

    #return all extra data if called without args 
    return $self->{my_extra_data} unless @_; 

    my $key = shift; 
    if (@_) { 
     $self->{my_extra_data}{$key} = shift; 
    } 

    return $self->{my_extra_data}{$key}; 
    }; 
} 

$book->extra_data(author => $author); 

#then later 

my $stored_author = $book->extra_data('author'); 
+0

'prefetch'用於'JOIN's(即'SELECT's),而我有不同的用例。我已經有一個相關的對象,並希望它存儲在新創建的對象(它有外鍵),以便它不需要再次檢索(在不同的文件/代碼範圍內) – 2012-08-15 17:13:29

+0

好的,所以你有一些將行對象返回到另一個作用域的代碼(否則你需要另一個'SELECT')。你不能只是返回兩個對象而不是一個?也許你想返回一個包含兩者的集合「對象」? 我在說的是,無論你移動你的行對象的任何渠道,你都應該能夠移動,我會想。 – 2012-08-15 17:26:00

相關問題