astritzeqiri / laravel-searchable
一个用于在 Laravel Eloquent 模型上进行搜索的 PHP 特性
1.0.2
2017-03-02 12:52 UTC
Requires
- php: >=5.4.0
- laravel/framework: 5.*
This package is not auto-updated.
Last update: 2024-09-14 19:42:26 UTC
README
一个用于在 Laravel Eloquent 模型上进行搜索的 PHP 特性
要求
- PHP >= 5.4
- Laravel >= 5.0
安装
将 laravel-searchable 添加到您的 composer.json 文件中
"require": { "astritzeqiri/laravel-searchable": "~1.0" }
让 composer 安装该包
$ composer require astritzeqiri/laravel-searchable
使用方法
示例
首先,您需要前往您的模型并使用 Searchable 特性
// E.x. User.php // add this before the class declaration use AstritZeqiri\LaravelSearchable\Traits\Searchable; // after the class declaration add this code snippet: use Searchable;
基本搜索
// This gives you a list of users that match the name john $users = App\User::search('John', ['name'])->get(); // if you want the search to be exact you pass a third attribute $users = App\User::search('John', ['name'], true)->get();
搜索字段数组也可以在模型本身上设置,例如 User.php
class User extends Model { // These are the default search fields. protected static $searchOn = ['first_name', 'last_name']; } // Now you can do this. // That gives you the users with the first_name or last_name Doe $users = App\User::search('Doe')->get(); // Of course if you give it the second attribute it ignores the model fields. // Now it only searches on the first_name not the last_name $users = App\User::search('Doe', ['first_name'])->get();
有时您可能想搜索一些不在用户模型上但与用户相关联的其他表中的字段
// Ex. You want to search users profile description which is contained in the profiles table, // you can do that by giving for example profile_description asf field. $users = App\User::search('Texas', ['profile_description'])->get(); // And then you'll have to declare a scope function on you User model for that field. // The function has to be called 'scopeSearchOn' and your field on studly_case // in this example it needs to be 'scopeSearchOnProfileDescription' class User extends Model { /** * Search on the users profile description. * * @param QueryBuilder $query * @param string $search [the string that we are searching for] * @param string $exact [if exact searching has been required] * * @return QueryBuilder $query */ public function scopeSearchOnProfileDescription($query, $search, $exact) { return $query->whereHas('profile', function($query) use($search) { return $query->where('description', 'LIKE', $search); }); } }