我有一个完美的搜索查询(我删除了一些不重要的代码):
$posts = new Post;
if(Input::has('query')) {
// Search for posts with title or tags matching the given criteria
$posts = $posts
->addSelect(DB::raw("MATCH(posts.title) AGAINST (?) as post_score"))
->addSelect(DB::raw("MATCH(tags.title) AGAINST (?) as tag_score"))
->where(function($query) {
return $query
->whereRaw('MATCH(posts.title) AGAINST (?)')
->orWhereRaw('MATCH(tags.title) AGAINST (?)');
})
->orderBy(DB::raw('post_score+tag_score'), 'desc')
->setBindings([ $input['query'], $input['query'], $input['query'], $input['query'] ]);
}
但是,只要我在上面的if()
语句之前添加这段代码:
if(Input::has('filter')) {
$posts = $posts->whereType($input['filter']); //Filter type by either 'article' or 'question'
}
...我收到此错误:
[2014-11-04 19:28:18] production.ERROR: PDO error: SQLSTATE[HY093]: Invalid parameter number (SQL: select `posts`.*, COALESCE(SUM(post_votes.rating), 0) as rating, MATCH(posts.title) AGAINST (css) as post_score, MATCH(tags.title) AGAINST (css) as tag_score from `posts` left join `post_tags` on `post_tags`.`post_id` = `posts`.`id` left join `tags` on `tags`.`id` = `post_tags`.`tag_id` left join `post_votes` on `post_votes`.`post_id` = `posts`.`id` where `type` = css and (MATCH(posts.title) AGAINST (css) or MATCH(tags.title) AGAINST (?)) group by `posts`.`id` order by post_score+tag_score desc, `views` desc) [] []
我输入css
作为搜索查询,应在question
上过滤该类型。正如您所看到的那样,变量没有正确绑定(对此没有正确的解释)。怎么会这样?我也试过这个不起作用的东西:
->where(function($query) use ($input) {
return $query
->whereRaw('MATCH(posts.title) AGAINST (?)', [$input['query']])
->orWhereRaw('MATCH(tags.title) AGAINST (?)', [$input['query']]);
})
提前致谢。
答案 0 :(得分:1)
这就是你需要的:
if(Input::has('filter')) {
$posts->whereType($input['filter']); //Filter type by either 'article' or 'question'
}
if(Input::has('query')) {
// no need for this:
// $posts = $posts
// just:
$posts
->addSelect(DB::raw("MATCH(posts.title) AGAINST (?) as post_score"))
->addBinding($input['query'], 'select')
->addSelect(DB::raw("MATCH(tags.title) AGAINST (?) as tag_score"))
->addBinding($input['query'], 'select')
->where(function($query) use ($input) {
$query
->whereRaw('MATCH(posts.title) AGAINST (?)', [$input['query']])
->orWhereRaw('MATCH(tags.title) AGAINST (?)', [$input['query']]);
})
->orderBy(DB::raw('post_score+tag_score'), 'desc')
}