[CDBI] one to one relationship

David Westbrook dwestbrook at tungstenlearning.com
Tue Jun 13 10:43:38 BST 2006


I think this should do what you want:
( ==> as a side note don't use "timestamp" as a column name since it's a 
reserved word .. maybe "created_date" or "query_timestamp" or something)

package Foo::DBI;
use base 'Class::DBI';
__PACKAGE__->connection( ... );

package Foo::RequestedQuery;
use base 'Foo::DBI';
__PACKAGE__->table('requested_queries');
__PACKAGE__->columns( Primary => qw/requested_query_id/ );
__PACKAGE__->columns( Essential => qw/query_id firstname surname email/);

package Foo::Query;
use base 'Foo::DBI';
__PACKAGE__->table('queries');
__PACKAGE__->columns( Primary => qw/query_id/ );
__PACKAGE__->columns( Essential => qw/search timestamp /);
__PACKAGE__->has_many( requested => 'Foo::RequestedQuery' );

#########
package main;
my $q = Foo::Query->retrieve( $query_id );
$q->add_to_requested({
  firstname => 'Joe',
  surname => 'Bloggs',
  query_id => $query_id,
  email => $email,
});

#########
Note also that, in general, you can pass a hashref to create:
my $new_row = Foo::Bar->create({ blah => 1234, stuff => 'qwe', some_id 
=> $x });

--david

brett gardner wrote:

> What is the best way to define a one to one relationship in Class::DBI?
>
> I have a table of queries where a user can do a basic search for 
> services. Then, if they want more information on their search, they 
> can fill in their details which populates a request. Nine times out of 
> ten the user will not be requesting any more info so I have created 
> two tables, "queries" and "requested_queries".
>
> queries
> -------------
> | query_id  |
> | search    |
> | timestamp |
> -------------
>
> requested_queries
> ----------------------
> | requested_query_id |
> | query_id           |
> | firstname          |
> | surname            |
> | email              |
> ----------------------
>
> Now is there anyway in Class::DBI to setup a relationship whereby I 
> could code the following (for an existing query that does not yet have 
> a matching requested query)
>
> $query->requested_query->create();
> $query->requested_query->firstname('Joe');
> $query->requested_query->surname('bloggs');
> $query->requested_query->update();
>
> I tried using "might_have", but this fails as both the "firstname" and 
> "surname" are required fields. And as soon as I call 
> "$query->firstname('joe');" it tries to run the insert statement 
> without waiting for the "$query->update" call.
>
> Cheers
>





More information about the ClassDBI mailing list