[Dbix-class] How to create a row object that contains related objects in DBIx::Class?

Will Crawford billcrawford1970 at gmail.com
Thu Aug 16 10:13:10 GMT 2012


On 16 August 2012 08:42, Jan Grmela <jan.grmela at imakers.cz> wrote:
> Hi Eugene,
> I'm pretty sure this should help you:
> http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/ResultSet.pm#cache

Not quite. What he's saying is, he wants $book->author to return the
author object that was supplied when he created the book (which would
make complete sense, since he passed it in as the "author" parameter
in the hashref).

It's a surprisingly common pattern - you want the related objects to
be available to methods on the new object; it's wasteful to fetch them
all afresh from the database if you had them already; and having to
pass them around along with the new object "just in case they're
useful" is, well, lots of extra code. If you've retrieved the object
from the database, sure, you can add "prefetch" if it's going to save
some extra work; but in this case, prefetch would still be pulling
data from the db that you *already have*.

> 2012/8/16 Eugene Yarmash <e.yarmash at gmail.com>:
...
>> When you create a Row object in DBIx::Class you can pass related objects as
>> values, e.g.
>>
>> my $author = $authors_rs->find(1);
>> my $book = $books_rs->create({ author => $author, title => 'title' });
>>
>> However, if you later use the author accessor, the object is retrieved again
>> from the database. Is it possible to create an object so that the related
>> object can be accessed without the additional query?



More information about the DBIx-Class mailing list