karupanerura / Aniki

The ORM as our great brother.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

複合FOREIGN KEYが貼られているtableをprefetchするとN+1になる

Hirofumi-Narita opened this issue · comments

schemaで複合FOREIGN KEYを貼っているtableをprefetchしようとすると、N+1になります。
https://github.com/karupanerura/Aniki/blob/master/lib/Aniki/Schema/Relationship/Fetcher.pm#L81-L84

例:
例えば、table_atable_b, table_abtable_ab_hogeが存在していて、

create_table 'table_ab' => columns {
    integer 'id', primary_key, auto_increment;
    integer 'table_a_id';
    integer 'table_b_id';

    fk ['table_a_id', 'table_b_id'], 'table_ab_hoge' => ['table_a_id', 'table_b_id'];
};

create_table 'table_ab_hoge' => columns {
    integer 'id', primary_key, auto_increment;
    integer 'table_a_id';
    integer 'table_b_id';
};

のようなtableがある時に、

my @result = $db->select(table_ab => +{ }, +{
    prefetch => [qw/table_ab_hoge/],
})->all;

のように使うと、

https://github.com/karupanerura/Aniki/blob/master/lib/Aniki/Schema/Relationship/Fetcher.pm#L81-L84

この場所がN+1になります。

English following Japanese:

複数カラムのFKではN+1問題が発生します。これは現状のアプローチでは解決が困難な問題です。
これ使い単一カラムの関係性を表現する名前を別途定義する方法を検討してみてはどうでしょう?
https://metacpan.org/pod/Aniki::Schema::Relationship::Declare

Title: When using multiple column foreign key, N+1 problem is occurred in prefetch

Result:

Yes. N+1 problem is occured with multiple column foreign key. This is a difficult problem to solve with the current approach.
How about use it for define a name that expresses the relationship of a single column?
https://metacpan.org/pod/Aniki::Schema::Relationship::Declare

ありがとうございます!!別途定義を作成してみます 🙇

Thank you so much!!