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

It's probably a noob question, but I need to ask ! Say I have two tables in a database :

some_types ( id serial primary key, name ); some_objects ( id serial primary key, name, some_type_id, CONSTRAINT fk1 FOREIGN KEY (some_type_id) REFERENCES some_types(id) );

I have a Catalyst application to create a new object such that the values passed back to the controller are a new object name and a type_name. The correct belongs_to and has_many relationships are defined. Obviously I can search some_types to find the some_types.id corresponding to the passed some_types.name value, and then insert these into some_objects : e.g.

my $object = $c->model('DB')->resultset('SomeObjects')->create({ name => $name, some_type_id => $id });

but there has to be a better way. The DBIx::Class::ResultSet documentation refers to this in the create() method : "To create one row for this resultset, pass a hashref of key/value pairs representing the columns of the table and the values you wish to store. If the appropriate relationships are set up, foreign key fields can also be passed an object representing the foreign row, and the value will be set to its primary key." However the documentation does not give examples, nor have I been able to find one. Can somebody help ? I'm sure it's not difficult, I just can't work out the right syntax. Thanks

Replies are listed 'Best First'.
Re: Inserting rows with a foreign key using DBIx::Class
by roboticus (Chancellor) on Apr 24, 2013 at 10:14 UTC

    fshrewsb:

    I've never used DBIx::Class, but I'd bet that if you look in the test suite for it, you'll find an example of foreign key insertion. Most of the popular modules on CPAN are pretty well tested, and should have a test case for anything explicitly mentioned in the documentation.

    (For some reason, I can't seem to find DBIx::Class on CPAN right now, it comes back with "No results", so I can't pinpoint the test for you. In fact, CPAN doesn't find "Spreadsheet::ParseExcel", "Spreadsheet", "DBI" or "Data::Dumper" right now. It's returning "No results" for all my search terms at the moment.)

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.