• 追加された行はこの色です。
  • 削除された行はこの色です。
* DBIC リレーション [#pe86a3db]

** 1対N [#q4324960]
選手とその所属チームを表すplayerテーブルとteamテーブルを想定すると、以下のようなコードになる。    

 package MyappDB::Player;
 
 use base 'DBIx::Class';
 
 __PACKAGE__->load_components(qw/ PK::Auto Core/);
 __PACKAGE__->table('player');
 __PACKAGE__->add_columns(qw/
 player_id
 name
 age
 team_id
 /);
 __PACKAGE__->set_primary_key('plyaer_id');
 __PACKAGE__->belongs_to(team => 'MyappDB::Team', 'team_id');
 
 1;

belongs_to()でリレーションを張り、第一引数のキーであるteamがアクセサになる。つまり、以下のようなコードでteamテーブルにアクセスできる。

 $rs = $rs->search();
  while (my $p = $rs->next) {
       print $p->name;
       print $p->team->team_name;
  }

teamテーブルにteam_idカラムがなくteam_noカラムだった場合、あるいはteamテーブルのプライマリーキー以外のカラムと外部結合している場合、以下のようにすることでJOINで使うカラムを明示できる。

  __PACKAGE__->belongs_to(team => 'MyappDB::Team', { 'foreign.team_no' => 'self.team_id' });


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS