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


In reply to Inserting rows with a foreign key using DBIx::Class by fshrewsb

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.