How can I select only specific columns when using prefetch in DBIx-Class?

社会主义新天地 提交于 2019-12-06 03:01:16

Yes, you are right. You can only select columns in the primary table, and can not get specific columns in the joined tables. What you need is join. use join and '+select','+as' property, you can select special columns from two tables.

Prefetch is used to select all columns from the prefetch tables as well. It is more efficient to use prefetch when you actually need those columns, e.g. so you can do $cd->artist->name without needing it to do the additional query. But if you don't need those columns then you have an unnecessary performance hit for loading up that data.

Version 0.08250 of DBIx::Class supports prefetching a subset of columns. Now you can write a query with join, columns and the new collapse attribute which works like prefetch:

my $rs = $schema->resultset('CD')->search(
  {},
  {
    join     => [qw/ artist /],
    columns  => [qw/ title artist.name /],
    collapse => 1,
  }
);

Additional. If you want to specify columns for nested joins (2 levels deep or more), you need to specify the columns using the hash format so that DBIx can resolve the relationships to apply to the column.

Example:

    my $rs = $schema->resultset('CD')->search(
      {},
      {
        join     => { 'artist' => { 'agent' => 'publisher' } },
        columns  => [qw/ title artist.name artist.agent.publisher_id /, 
                        { 'artist.agent.publisher.publisher_name' => 'publisher.publisher_name' } ],
        collapse => 1,
      }
    );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!