[Dbix-class] Adding stuff via many-to-many relationships

Justin Guenther jguenther at gmail.com
Wed Jun 14 20:27:57 CEST 2006


Hello Robert,

On 6/13/06, Robert Norris <rob at cataclysm.cx> wrote:
> Part of my database is a list of users, and a list of groups. Each group
> can have multiple user, and each user can be in multiple groups. I've
> set up a fairly standard many-to-many relationship (ie two tables with a
> link table). Schema proper is here: http://pastebin.com/707955.
>
> Anyway, I'm wondering what the best practice is for adding things to the
> database via many-to-many relationships. Consider the case of creating a
> new group, and putting a new user in it. This obviously works:
>
>     my $g = $s->resultset("Group")
>               ->create({name => "caped crusaders"});
>     $g->update;

As an aside, that update() call is completely unnecessary.
$obj->create() is a shortcut to $obj->new()->insert(), which will do
an INSERT into the object's table. It would only be necessary to call
update() if you changed one or more of the object's columns after
inserting it. As it stands, if there are no changed columns update()
is a no-op.

>     my $u = $s->resultset("User")
>               ->create({name => "superman"});
>     $u->update;
>
>     $s->resultset("GroupUser")
>       ->create({f_group => $g->groupid, f_user => $u->userid});
>
> That seems rather clunky though. Why should I have to care about the
> contents of the link table when DBIC already knows how these are linked
> together.

This is a known difficulty, and is currently being worked on and will
hopefully be done before 0.07 is released. Works has been interfering
with my time for this, but this feature will be incredibly useful to
me for the project I'm working on right now at work, which will give
me some incentive to get it done.

I agree it is rather klunky, but this is on the TODO list and there
should hopefully be a testing version of it soon.


   Justin


> I tried this to add the user:
>
>     my $u = $g->users->create({name => "superman"});
>
> But I get this:
>
>     DBIx::Class::ResultSet::create(): No such column f_group on Emma::Schema::User
>
> Did I screw my schema? They do look right to me, but the docs are a
> little thin on this.
>
> What is the "correct" way to do add stuff while also updating the link
> table?
>
> Rob.
>
>
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.3 (GNU/Linux)
>
> iD8DBQFEj6MlWb13Z/wY5sIRAjpNAKCMPzoqU4qs7+xwN+Ak0vLm4/M9qACglmtr
> U0jcJhoevdxKsuw44UMIimo=
> =K6tP
> -----END PGP SIGNATURE-----
>
>
> _______________________________________________
> List: http://lists.rawmode.org/cgi-bin/mailman/listinfo/dbix-class
> Wiki: http://dbix-class.shadowcatsystems.co.uk/
> IRC: irc.perl.org#dbix-class
> SVN: http://dev.catalyst.perl.org/repos/bast/trunk/DBIx-Class/
> Searchable Archive: http://www.mail-archive.com/dbix-class@lists.rawmode.org/
>
>



More information about the Dbix-class mailing list