[Dbix-class] Why does $cd->set_genres() take only objects?

Bill Moseley moseley at hank.org
Thu Sep 17 14:48:29 GMT 2009


I'm trying to better understand many_to_many sugar methods.  Specifically,
why I cannot pass a list of ids to a set_$rel

In the familiar "music" database each Cd can have one or more Genres.

Cd->many_to_many( genres =3D> 'cd_genres' =3D> 'genre' );

What I'm wondering is why I cannot use ids directly like $cd->set_genres(
[2, 3] );
Instead I have to supply Genre objects:

my @genres =3D $schema->resultset('Genre')->search({ id =3D> [2,3]});
$cd->set_genres( \@genres );

But, that results in these queries where the select is apparently only there
fetch the ids of the Genre objects, which I already have.

SELECT me.id, me.name FROM genre me WHERE ( ( id =3D ? OR id =3D ? ) ): '2'=
, '3'
DELETE FROM cd_genre WHERE ( cd =3D ? ): '1'
INSERT INTO cd_genre ( cd, genre) VALUES ( ?, ? ): '1', '2'
INSERT INTO cd_genre ( cd, genre) VALUES ( ?, ? ): '1', '3'

Is that select necessary for DBIC to work?
(I suppose an additional optimization would be to do the INSERTs in a single
db operation.)

The reason I'm curious is I have only the $cd object, the "genres" name, and
the @ids.  So I don't have the "Genre" moniker.
So, it ends up:

          my ($key) =3D
$cd->genres->result_source->primary_columns;$cd->set_genres(
$cd->genres->result_source->resultset->search({ $key =3D> \@ids}) );

Sorry, if that's the hard way to do that -- all the class relationships in
DBIx::Class are still a bit fuzzy to me.

Anyway, that seems like a bit of work to just fetch the ids (which I already
have).


Also, if all I have is $schema, the "Cd" moniker, and the (non-)relation for
the many_to_many "genres" is this the recommended way to get a list of all
Genre objects?

$schema->resultset( 'Cd'
)->new_result({})->genres->result_source->resultset->all;

Thanks,

-- =

Bill Moseley
moseley at hank.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.scsys.co.uk/pipermail/dbix-class/attachments/20090917/5ba=
61677/attachment.htm


More information about the DBIx-Class mailing list