php Laravel 4/5 搜索表单如

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18283714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:17:19  来源:igfitidea点击:

Laravel 4/5 search form like

phplaravellaravel-4laravel-5

提问by erm_durr

I have a search form and functions, all done. Just to ask, is it possible to do it in Eloquent a query like this:

我有一个搜索表单和功能,全部完成。只是想问一下,是否可以在 Eloquent 中执行这样的查询:

SELECT * FROM players WHERE name LIKE '%".$name."%'

To display some possible matching names. My current controller function:

显示一些可能的匹配名称。我目前的控制器功能:

    public function search()
{
    $name = Input::get('character');
    $searchResult = Player::where('name', '=', $name)->paginate(1);
    return View::make('search.search')
            ->with('name', $name)
            ->with('searchResult', $searchResult);
}

And my view:

而我的观点:

    <form id="custom-search-form" class="form-search form-horizontal pull-right" action="{{ URL::action('CharactersController@search') }}" method="get">
    <div class="input-append spancustom">
        <input type="text" class="search-query" name="character" placeholder="Character/guild name">
        <button type="submit" class="btn"><i class="icon-search"></i></button>
    </div>
</form>

Thanks in advance.

提前致谢。

回答by rmobis

Hmmm, yes, just set likeas your comparison operator, and send the string with %'s. Something like this:

嗯,是的,只需设置like为您的比较运算符,并发送带有%'s的字符串。像这样的东西:

Player::where('name', 'LIKE', "%$name%")->get();

回答by Yaroslav

If you need to frequently use LIKE, you can simplify the problem a bit. A custom method like () can be created in the model that inherits the Eloquent:

如果你需要经常使用LIKE,你可以把问题简化一点。可以在继承 Eloquent 的模型中创建像 () 这样的自定义方法:

public  function scopeLike($query, $field, $value){
        return $query->where($field, 'LIKE', "%$value%");
}

So then you can use this method in such way:

那么你可以这样使用这个方法:

 User::like('name', 'Tomas')->get();

回答by mnv

With quote of string:

用字符串引用:

$value = DB::connection()->getPdo()->quote('%' . strtolower($value) . '%');
$query->whereRaw('LOWER(your_table.your_column) LIKE ' . $value);

回答by Fokwa Best

public function get_student($match){
    return Student::where('name', 'like', $match .'%');
}

Try the above

试试上面的