Perl DBIx::Class按ID从另一个表获取行
在我的项目中,我有3张表格:艺术家、专辑和曲目 结果艺术家:Perl DBIx::Class按ID从另一个表获取行,perl,dbix-class,Perl,Dbix Class,在我的项目中,我有3张表格:艺术家、专辑和曲目 结果艺术家: ... __PACKAGE__->has_many( 'albums' => 'MYLIB::DB::Schema::Result::MyDir::Album', { 'foreign.artist_id' => 'self.id', }, ); ... ... __PACKAGE__->belongs_to( 'artist' => 'MYLIB::DB::Schema:
...
__PACKAGE__->has_many(
'albums' => 'MYLIB::DB::Schema::Result::MyDir::Album',
{ 'foreign.artist_id' => 'self.id', },
);
...
...
__PACKAGE__->belongs_to(
'artist' => 'MYLIB::DB::Schema::Result::Artist',
{ 'foreign.id' => 'self.artist_id', },
);
__PACKAGE__->has_many(
'tracks' => 'MYLIB::DB::Schema::Result::MyDir::Track',
{ 'foreign.album_id' => 'self.id', },
);
...
__PACKAGE__->belongs_to(
'album' => 'MYLIB::DB::Schema::Result::MyDir::Album',
{ 'foreign.id' => 'self.album_id', },
);
结果专辑:
...
__PACKAGE__->has_many(
'albums' => 'MYLIB::DB::Schema::Result::MyDir::Album',
{ 'foreign.artist_id' => 'self.id', },
);
...
...
__PACKAGE__->belongs_to(
'artist' => 'MYLIB::DB::Schema::Result::Artist',
{ 'foreign.id' => 'self.artist_id', },
);
__PACKAGE__->has_many(
'tracks' => 'MYLIB::DB::Schema::Result::MyDir::Track',
{ 'foreign.album_id' => 'self.id', },
);
...
__PACKAGE__->belongs_to(
'album' => 'MYLIB::DB::Schema::Result::MyDir::Album',
{ 'foreign.id' => 'self.album_id', },
);
结果跟踪:
...
__PACKAGE__->has_many(
'albums' => 'MYLIB::DB::Schema::Result::MyDir::Album',
{ 'foreign.artist_id' => 'self.id', },
);
...
...
__PACKAGE__->belongs_to(
'artist' => 'MYLIB::DB::Schema::Result::Artist',
{ 'foreign.id' => 'self.artist_id', },
);
__PACKAGE__->has_many(
'tracks' => 'MYLIB::DB::Schema::Result::MyDir::Track',
{ 'foreign.album_id' => 'self.id', },
);
...
__PACKAGE__->belongs_to(
'album' => 'MYLIB::DB::Schema::Result::MyDir::Album',
{ 'foreign.id' => 'self.album_id', },
);
现在我有了一个对象$artist
,我想按ID获得一个曲目
查询示例:
从track\u id=$x的曲目中选择*我假设该曲目位于您的$artist
专辑中。查询可以通过连接三个表来完成。看
这是一个未经测试的例子
my $tracks = $artist->search_related(
{
id => $my_track_id,
},
{
join => { albums => 'tracks' },
}
);
如果您的曲目不一定是由$artist提供的,那么直接查询曲目可能更有意义。如果您想生成您提供给我们的SQL,那么您拥有一个artist对象这一事实就无关紧要了。只需获取一个曲目结果集,然后在上面运行find()
my $track_rs = $schema->resultset('Track');
my $track = $track_rs->find($track_id);
如果由于某种原因,您没有模式对象,那么您可以从您的艺术家对象获得它
my $schema = $artist->result_source->schema;