[Dbix-class] How to avoid find when create related records

Roman Daniel roman.daniel at davosro.cz
Sat Feb 3 16:05:06 GMT 2018


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";
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.scsys.co.uk/pipermail/dbix-class/attachments/20180203/9dad0f20/attachment.htm>


More information about the DBIx-Class mailing list