我正在开发一个可以使用Catalyst框架通过浏览器访问的MySQL数据库。用户可以使用特定ID(车牌)和/或特定车辆颜色从搜索框中搜索数据库。
问题在于,当我搜索数据库中存在的某些ID时,它们不会显示在结果中,而其他ID会显示在结果中。如果我手动更改浏览器中的URL,我可以正确访问我测试的所有ID,所以我猜问题就在于我的搜索功能。
我在控制器中的功能就是这个
sub search : Local : Args(0) {
my ($self, $c) = @_;
my $schema = $c->model('DB');
my $car_plate = $c->request->params->{car_plate} || 'N/A';
my $car_model = $c->request->params->{car_model} || 'N/A';
my $result_set = "";
my $result_set_count = 0;
if (($car_plate ne 'N/A') && ($car_model ne 'Select model')) { # car plate AND car model entered
$result_set = [
$schema->resultset('Car')->search({
'plates' => { 'like', '%' . $car_plate . '%' },
'colors' => $car_model
},
)->all
];
}
elsif (($car_plate eq 'N/A') && ($car_model ne 'Select model')) { # car plate blank, car model entered
$result_set = [
$schema->resultset('Car')->search(
{ 'colors' => $car_model },
)->all
];
}
elsif (($car_plate ne 'N/A') && ($car_model eq 'Select model')) { # car plate entered, car model blank
$result_set = [
$schema->resultset('Car')->search(
{ 'plates' => { 'like', '%' . $car_plate . '%' } },
)->all
];
}
if (($car_plate ne 'N/A') && ($car_model ne 'Select model')) {
$result_set_count = $c->model('DB::Car')->search({
'plates' => { 'like', '%' . $car_plate . '%' },
'colors' => $car_model
}
)->all;
}
elsif (($car_plate eq 'N/A') && ($car_model ne 'Select model')) {
$result_set_count = $c->model('DB::Car')->search({ 'colors' => $car_model })->all;
}
elsif (($car_plate ne 'N/A') && ($car_model eq 'Select model')) {
$result_set_count = $c->model('DB::Car')->search({ 'plates' => { 'like', '%' . $car_plate . '%' } })->all;
}
my $error_message = "";
if ($result_set_count == 0) {
$error_message = "<p>Not found</p>";
$c->stash(
errorcount => $error_message,
Cars => $result_set,
template => 'cars/search_no_results.tt'
);
}
else {
$c->stash(
errorcount => $error_message,
Cars => $result_set,
template => 'cars/search_cars.tt'
);
}
$c->response->header('Cache-Control' => 'no-cache');
}
答案 0 :(得分:3)
$ result_set_count将是一个数组(你实际上并没有使用count()函数)
替换
之类的行$result_set_count = $c->model('DB::Car')->search({ 'plates' => { 'like', '%' . $car_plate . '%' } })->all;
通过
$result_set_count = $c->model('DB::Car')->count('plates' => { 'like', '%' . $car_plate . '%' });
然后,通过执行一次数据库查询来优化代码:
my $rs = $c->model('DB::Car')->search_rs({ ... }, { });
my $count = $rs->count;
my $set = [ $rs->all ];
答案 1 :(得分:0)
您是否尝试过获取DBIx :: Class生成的SQL输出,然后直接在MySQL中运行它?
请参阅:Can I pretty-print the DBIC_TRACE output in DBIx::Class?