[Catalyst] DBIx::Class and Catalyst - Trying to make sense of it all.

Matt S Trout dbix-class at trout.me.uk
Mon Sep 29 17:05:05 BST 2008

On Sun, Sep 28, 2008 at 10:15:25AM -0400, Leanan Sidhe wrote:
> First, I apologize for the completely noob tone of this email.  I've read
> through the perl docs for DBIx::Class, and various Catalyst parts, but I'm
> having problems understanding how DBIx::Class stuff is slightly different in
> Catalyst.
> For example, in the DBI docs, I constantly see the following:
> $schema->resultset('table_name')->search(....);

No you don't.

The argument to resultset is the source name, which is by default the last
part of the class name.

So for My::Schema::Foo, it'd be $schema->resultset('Foo'), the table name
could be 'tbl_foobar_baz' or whatever for all DBIx::Class cares so long as
you pass that to ->table.

> in Catalyst, this seems to be
> $c->model('table_model_package')->search(....);

No. Basically for each valid argument to $schema->resultset,
Catalyst::Model::DBIC::Schema sets it up so that

$c->model('NameOfModel::${arg_to_resultset}') is a shortcut to

> I get that and it's not too rough.
> But then where I get hung up is that I have a few table relationships I want
> to query.  Say I have the following tables / relationships:
> users:
>   user_id
>   user_name
>   pass
> cards:
>   card_id
>   card_name
>   card_description
>   set_id
> sets:
>   set_id
>   set_name
> user_cards:
>   id
>   user_id
>   card_id
> A card has a set
> A set has many cards
> A card has many user_cards
> A user_card has a user
> A user_card has a card
> Now, say I want to have a page that lists out all the cards a user has.
> Right now I have one user, so I'm not doing much on the user id.  Ok, that's
> simple, I just do:
> my $user_cards = $c->model('Model::for::UserCards');
> my $cards = $user_cards->search_related('cards');

That's completely wrong.

What you want is:

my $user = $c->model('ModelName::User')->find($user_id);

my $cards = $user->cards;

If you're using Catalyst::Authentication::Store::DBIx::Class you can do

my $user = $c->user->obj;

to get the DBIC object for the user.

If you want more information on using DBIx::Class, please post to the
DBIx::Class list - the $c->model shortcut for $schema->resultset is the
-only- thing that's different between normal DBIC usage and DBIC under
Catalyst, and that's not so much a difference as an extra handy feature :)

      Matt S Trout       Need help with your Catalyst or DBIx::Class project?
   Technical Director                    http://www.shadowcat.co.uk/catalyst/
 Shadowcat Systems Ltd.  Want a managed development or deployment platform?
http://chainsawblues.vox.com/            http://www.shadowcat.co.uk/servers/

More information about the Catalyst mailing list