Class::DBIで複数テーブルにまたがった検索(Class::DBI::View編)
katoさんより、
どうしてもリレーションがアレな
複数のテーブルをCDBIでキレイに扱いたければ
Class::DBI::Viewがいいかもしれませんね。
と、アドバイスいただいたので試しました。
./NekoView/DBI.pl
package NekoView::DBI;
use strict;
use warnings;
use base 'Class::DBI';
__PACKAGE__->connection('dbi:mysql:nekodb', 'nekokak', '******');
1;
./NekoView/PageImage.pm
package NekoView::PageImage;
use strict;
use warnings;
use base 'NekoView::DBI';
use Class::DBI::View qw(TemporaryTable);
__PACKAGE__->setup_view(<<SQL);
SELECT pages.page_id ,pages.title ,pages.date_to_publish ,pages.date_to_archive
,images.image_id ,images.name ,images.position ,images.filename
FROM pages , images
WHERE pages.page_id = images.page_id
SQL
__PACKAGE__->columns( Essential => qw[page_id title date_to_publish date_to_archive image_id name position filename]);
__PACKAGE__->columns( Primary => qw[page_id]);
1;
./test-view.pl
#! /usr/bin/perl
use strict;
use warnings;
use NekoView::PageImage;
use Data::Dumper;
my $result = NekoView::PageImage->search('page_id' => 1);
print Dumper($result);
$result = NekoView::PageImage->search('page_id' => 1 ,'image_id' => 2);
print Dumper($result);
$result = NekoView::PageImage->retrieve_all;
print Dumper($result);
なるほどです、望む結果が得られました。
結果、
$VAR1 = bless( {
'_data' => [
{
'date_to_publish' => 'dd/mm/yyyy',
'filename' => 'cdbi.gif',
'date_to_archive' => '',
'image_id' => '1',
'page_id' => '1',
'name' => 'Class::DBI logo',
'position' => 'http://www.hoge.com/images/',
'title' => 'Extending Class::DBI'
},
{
'date_to_publish' => 'dd/mm/yyyy',
'filename' => 'cdbi-diagram.gif',
'date_to_archive' => '',
'image_id' => '2',
'page_id' => '1',
'name' => 'Class Diagram(CDBI)',
'position' => 'http://www.hoge.com/images/',
'title' => 'Extending Class::DBI'
}
],
'_place' => 0,
'_mapper' => [],
'_class' => 'NekoView::PageImage'
}, 'Class::DBI::Iterator' );
$VAR1 = bless( {
'_data' => [
{
'date_to_publish' => 'dd/mm/yyyy',
'filename' => 'cdbi-diagram.gif',
'date_to_archive' => '',
'image_id' => '2',
'page_id' => '1',
'name' => 'Class Diagram(CDBI)',
'position' => 'http://www.hoge.com/images/',
'title' => 'Extending Class::DBI'
}
],
'_place' => 0,
'_mapper' => [],
'_class' => 'NekoView::PageImage'
}, 'Class::DBI::Iterator' );
$VAR1 = bless( {
'_data' => [
{
'date_to_publish' => 'dd/mm/yyyy',
'filename' => 'cdbi.gif',
'date_to_archive' => '',
'image_id' => '1',
'page_id' => '1',
'name' => 'Class::DBI logo',
'position' => 'http://www.hoge.com/images/',
'title' => 'Extending Class::DBI'
},
{
'date_to_publish' => 'dd/mm/yyyy',
'filename' => 'cdbi-diagram.gif',
'date_to_archive' => '',
'image_id' => '2',
'page_id' => '1',
'name' => 'Class Diagram(CDBI)',
'position' => 'http://www.hoge.com/images/',
'title' => 'Extending Class::DBI'
}
],
'_place' => 0,
'_mapper' => [],
'_class' => 'NekoView::PageImage'
}, 'Class::DBI::Iterator' );
こういう検索をする場合ってClass::DBI::Viewをつかわなければいけないのでしょうか??