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 |