Using Eloquent ORM in Laravel to perform search of database using LIKE

前端 未结 5 1725
清歌不尽
清歌不尽 2020-12-04 15:14

I want to use Eloquent\'s active record building to build a search query, but it is going to be a LIKE search. I have found the User::find($term) or User:

相关标签:
5条回答
  • 2020-12-04 15:25

    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 ORM:

    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();
    
    0 讨论(0)
  • 2020-12-04 15:32

    FYI, the list of operators (containing like and all others) is in code:

    /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
    
    protected $operators = array(
        '=', '<', '>', '<=', '>=', '<>', '!=',
        'like', 'not like', 'between', 'ilike',
        '&', '|', '^', '<<', '>>',
        'rlike', 'regexp', 'not regexp',
    );
    

    disclaimer:

    Joel Larson's answer is correct. Got my upvote.

    I'm hoping this answer sheds more light on what's available via the Eloquent ORM (points people in the right direct). Whilst a link to documentation would be far better, that link has proven itself elusive.

    0 讨论(0)
  • 2020-12-04 15:34

    Use double quotes instead of single quote eg :

    where('customer.name', 'LIKE', "%$findcustomer%")
    

    Below is my code:

    public function searchCustomer($findcustomer)
    {
        $customer = DB::table('customer')
                      ->where('customer.name', 'LIKE', "%$findcustomer%")
                      ->orWhere('customer.phone', 'LIKE', "%$findcustomer%")
                      ->get();
    
        return View::make("your view here");
    }
    
    0 讨论(0)
  • 2020-12-04 15:41

    If you do not like double quotes like me, this will work for you with single quotes:

    $value = Input::get('q');
    $books = Book::where('name', 'LIKE', '%' . $value . '%')->limit(25)->get();
    
    return view('pages/search/index', compact('books'));
    
    0 讨论(0)
  • 2020-12-04 15:49

    You're able to do database finds using LIKE with this syntax:

    Model::where('column', 'LIKE', '%value%')->get();
    
    0 讨论(0)
提交回复
热议问题