使用Laravel 4创建搜索功能 [英] Creating search functionality with Laravel 4

查看:35
本文介绍了使用Laravel 4创建搜索功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为用户创建一种搜索网站上所有产品的方式.当他们搜索伯顿滑雪板"时,我只希望伯顿品牌的滑雪板出现在搜索结果中.但是,如果他们仅搜索"burton",则所有带有burton品牌的产品都应出现.

I am trying to create a way for users to search through all the products on a website. When they search for "burton snowboards", I only want the snowboards with the brand burton to appear in the results. But if they searched only "burton", then all products with the brand burton should appear.

这是我尝试编写的内容,但由于多种原因而无法使用.

This is what I have attempted to write but isn't working for multiple reasons.

控制器:

 public function search(){
    $input = Input::all();

    $v= Validator::make($input, Product::$rules);

    if($v->passes())
    {

        $searchTerms = explode(' ', $input);
        $searchTermBits = array();
        foreach ($searchTerms as $term) {
            $term = trim($term);
            if (!empty($term)){
                $searchTermBits[] = "search LIKE '%$term%'";
            }
        }
        $result = DB::table('products')
        ->select('*')
        ->whereRaw(". implode(' AND ', $searchTermBits) . ")
        ->get();

        return View::make('layouts/search', compact('result')); 
    }
    return Redirect::route('/');    
}

我正在尝试重新创建为此

I am trying to recreate the first solution given for this stackoverflow.com problem

我发现的第一个问题是我正在尝试爆炸$input,但是它已经是数组.因此,我不确定如何解决该问题.以我写->whereRaw(". implode(' AND ', $searchTermBits) . ")的方式,我确定这是不正确的.我不确定如何解决这些问题,任何见解或解决方案将不胜感激.

The first problem I have identified is that i'm trying to explode the $input, but it's already an array. So i'm not sure how to go about fixing that. And the way I have written the ->whereRaw(". implode(' AND ', $searchTermBits) . "), i'm sure isn't correct. I'm not sure how to fix these problems though, any insights or solutions will be greatly appreciated.

推荐答案

在构建数据库查询时,您需要从输入字段中获取术语并遍历所有术语.您还需要设置要在其中搜索术语的表字段,在此示例中,表字段为name.这是一个未经测试的示例,但是您会明白的.

You'll need to get the terms from your input field and loop through all of them while building your DB query. You'll also need to set the table field in which you want the terms to be searched, in this the example the table field is name. Here's an untested example but you'll get the idea.

public function search() {

    $q = Input::get('myInputField');

    $searchTerms = explode(' ', $q);

    $query = DB::table('products');

    foreach($searchTerms as $term)
    {
        $query->where('name', 'LIKE', '%'. $term .'%');
    }

    $results = $query->get();

}

这篇关于使用Laravel 4创建搜索功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆