DBIx::Classでhas_manyするとLEFT JOINになる
こういうデータベースを作って
CREATE TABLE table1( id integer PRIMARY KEY, data1 text ); CREATE TABLE table2( table1_id integer REFERENCES table1(id) PRIMARY KEY, data2 text ); INSERT INTO table1 VALUES(1, '1-1'); INSERT INTO table1 VALUES(2, '1-2'); INSERT INTO table2 VALUES(1, '2-1');
こういうスクリプトを
package TestDB::Schema; use base qw/DBIx::Class::Schema::Loader/; __PACKAGE__->loader_options( relationships => 1, debug => 1 ); 1; package main; my $schema1 = TestDB::Schema->connect("dbi:SQLite:dbname=testdb.db","","",undef); my @rs = $schema1->resultset('Table1')->search(undef, {join => ['table2s']} ); print "\n";
実行する。
% DBIC_TRACE=1 perl join.pl TestDB::Schema::Table1->load_components("PK::Auto", "Core"); TestDB::Schema::Table2->load_components("PK::Auto", "Core"); TestDB::Schema::Table1->table("table1"); TestDB::Schema::Table1->add_columns( "id", { data_type => "integer", is_nullable => 0, size => undef }, "data1", { data_type => "text", is_nullable => 0, size => undef }, ); TestDB::Schema::Table1->set_primary_key("id"); TestDB::Schema::Table2->table("table2"); TestDB::Schema::Table2->add_columns( "table1_id", { data_type => "integer", is_nullable => 0, size => undef }, "data2", { data_type => "text", is_nullable => 0, size => undef }, ); TestDB::Schema::Table2->set_primary_key("table1_id"); TestDB::Schema::Table1->has_many( "table2s", "TestDB::Schema::Table2", { "foreign.table1_id" => "self.id" }, ); TestDB::Schema::Table2->belongs_to("table1_id", "TestDB::Schema::Table1", { id => "table1_id" }); SELECT me.id, me.data1 FROM table1 me LEFT JOIN table2 table2s ON ( table2s.table1_id = me.id ):
DBIx::Class::RelationshipのperldocにもLEFT JOINを生成するとか書いてある。