Hello,

Is there a solution for the following (quite repeating for me) problem? I
have a table (customer) containing foreign key (address_id) to table
address. The rows in address table are just values, they do not represent
unique addresses. Two different customers have two different records (two
different ids) in address table.

When I create customer together with address and pass the adress as hashref
(which is very comfortable), the address resultset is first searched for
the values passed and only if the address is not found, new address is
created.

Is there a way to make DBIC skip the find and always create the related
record (while passing related record as plain hashref)?

Thanks for any info

Roman


# the tables (in SQLite are like)
create table customer (
   customer_id INTEGER PRIMARY KEY,
   name varchar(128) NOT NULL,
   address_id INTEGER NOT NULL
);

create table address (
   address_id INTEGER PRIMARY KEY,
   street varchar(128) NOT NULL,
   city varchar(128) NOT NULL
);

# The schema is like
use common::sense;

{

    package MyApp::Schema::Result::Customer;
    use base qw/DBIx::Class::Core/;

    __PACKAGE__->table('customer');
    __PACKAGE__->add_columns(qw/ customer_id name address_id /);
    __PACKAGE__->set_primary_key('customer_id');
    __PACKAGE__->has_one(
        'address',
        'MyApp::Schema::Result::Address',
        { 'foreign.address_id' => 'self.address_id' }
    );

    package MyApp::Schema::Result::Address;
    use base qw/DBIx::Class::Core/;

    __PACKAGE__->table('address');
    __PACKAGE__->add_columns(qw/ address_id street city/);
    __PACKAGE__->set_primary_key('address_id');

    package MyApp::Schema;
    use base qw(DBIx::Class::Schema);

    __PACKAGE__->register_class( 'Customer',
        'MyApp::Schema::Result::Customer' );
    __PACKAGE__->register_class( 'Address',
'MyApp::Schema::Result::Address' );
}

my $schema = MyApp::Schema->connect( 'dbi:SQLite:sample.db', '', '' );
my ( $c1, $c2 ) = map {
    $schema->resultset('Customer')->create(
        {
            name    => $_,
            address => {
                street => 'Axmanova 11',
                city   => 'Brno',
            }
        }
      )
} 'Pavel Petr', 'Petr Pavel';

warn $c1->address_id == $c2->address_id? "NOT OK": "OK";
_______________________________________________
List: http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/dbix-class
IRC: irc.perl.org#dbix-class
SVN: http://dev.catalyst.perl.org/repos/bast/DBIx-Class/
Searchable Archive: http://www.grokbase.com/group/dbix-class@lists.scsys.co.uk

Reply via email to