tqisjim has asked for the wisdom of the Perl Monks concerning the following question:

my @ids = ( 1, 2, 3, 4 ); my $rs = $schema->resultset('records'); my @records = $rs->find( @ids, { key => 'primary' } ); ## Throws the following error: ## !!! DBIx::Class::ResultSet::find(): find() expects ## either a column/value hashref, or a list of values ## corresponding to the columns of the specified unique ## constraint 'primary'

Documentation:

find Arguments: \%columns_values | @pk_values, { key => $unique_constraint, + %attrs }?

Based on the documentation and error message, it seems like my invocation is correct. What am I doing wrong?

Replies are listed 'Best First'.
Re: dbix::class find() question
by poj (Abbot) on Jan 18, 2016 at 16:56 UTC
    Find - Finds and returns a single row based on supplied criteria.

    Assuming the primary key is a single field try

    for my $id (@ids){ push @records, $rs->find( $id ); }
    poj
Re: dbix::class find() question
by Your Mother (Archbishop) on Jan 18, 2016 at 19:12 UTC

    poj is right already but I offer the other path–

    my $rs = $schema->resultset('records'); my @records = $rs->search({ id => \@ids });

    The only caveat I might offer here is that search won’t explicitly complain or fail if say only one of the ids is found. I would also suggest that you do this kind of thing instead–

    my $rs = $schema->resultset('records') ->search({ id => \@ids }); for my $row ( $rs->all ) {}

    As long as you remain in the realm of pure resultsets you don’t execute SQL. So working with them that way—RS until you are ready for records—is more flexible, extensible, and often more performant—as the biz-devs say—since you can end up hitting the DB less.

    Update! Didn’t use hasref args initially.

      is that statement equivalent to this?
      $rs = $schema->resultset('records') ->search({ id => { in => \@ids } }) ;

      The syntax in your example is a definite improvement!

        Sort of. The queries are different but what they return should be the same.

        # based on the usual DBIC example tables my @ids = (1..4); my $rs = $schema->resultset('Cd') ->search({ cd_id => \@ids }); warn "query: ", ${$rs->as_query()}->[0], "\n"; $rs = $schema->resultset('Cd') ->search({ cd_id => { in => \@ids } }); warn "query: ", ${$rs->as_query()}->[0], "\n"; __END__ query: (SELECT me.cdid, me.artistid, me.title, me.year FROM cd me WHER +E ( ( cd_id = ? OR cd_id = ? OR cd_id = ? OR cd_id = ? ) )) query: (SELECT me.cdid, me.artistid, me.title, me.year FROM cd me WHER +E ( cd_id IN ( ?, ?, ?, ? ) ))

        Yeppers (but see my syntax update). :P