0

Example

I have a table that might_have an expansion board; an expansion board has_many locks

Is it possible to when the might_have is first accessed to prefetch the locks?

(Yes I know that when I get the table I can prefetch the board and it's locks; just wondering if I have to do it this way.)

package Table;

__PACKAGE__->might_have("expansion_board", "ExpansionBoard",
{ "foreign.boardid" => "self.boardid" });

#etc.

package ExpansionBoard;

__PACKAGE__->has_many("locks","Lock",
{ "foreign.boardid" => "self.boardid" },
undef);

#etc.

package Lock;

#etc.

I would most like that $table->expansion_board on first access to also load in it's locks from the database.

melutovich
  • 372
  • 1
  • 3
  • 15
  • 1
    I don't understand the question. Can you please [edit] and clarify what you're trying to do. Please use proper inline-code markup for the things that are methods or config values. It's very hard to read your question. – simbabque Jul 29 '16 at 12:18
  • @simbabque updated; you can also look at nwellnhof's answer. – melutovich Jul 29 '16 at 13:26

1 Answers1

1

IIUC, you have something like

my $board = $result->expansion_board;

and want to prefetch the board's locks. In this case, you could use the search_related method with a prefetch attribute:

my $board = $result->search_related('expansion_board', undef, {
    prefetch => 'locks',
})->single;

Or you could try the find_related method:

my $board = $result->find_related('expansion_board', undef, {
    prefetch => 'locks',
});
nwellnhof
  • 32,319
  • 7
  • 89
  • 113
  • Does your prefetch cache the board and locks relationships, so that $result->expansion_board and $result->expansion_board->locks will not need the DB again? Is there a way to have this setup so that on the first occurrence of my $board = $result->expansion_board; would at the same time as loading in the expansion_board to also get the locks. (i.e. old code is using $result->expansion_board ) – melutovich Jul 29 '16 at 12:52
  • 1
    @melutovich (1) The only thing I know for sure is that `$board->locks` shouldn't hit the DB. I don't think other accesses through the original `$result` are cached. Try to run DBIC with SQL tracing and have a look at the statements it generates. (2) Maybe you could try to override the `expansion_board` method in the result class, but I wouldn't recommend that. – nwellnhof Jul 29 '16 at 13:05