vluzrmos/eloquent-simple-searchable

一个简单的 Eloquent 搜索范围。

v0.1.1 2021-08-31 14:20 UTC

This package is auto-updated.

Last update: 2024-08-29 03:29:35 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License

安装

composer require vluzrmos/eloquent-simple-searchable

用法

将这个特性放入你的模型中

namespace App;

use Illuminate\Database\Eloquent\Model;
use Vluzrmos\SimpleSearchable\Eloquent\SimpleSearchableTrait;

class User extends Model
{ 
	use SimpleSearchableTrait;

	protected $searchable = [
		'field' => 'type'
	];
}

属性 $searchable 应该包含一个索引和列或相关列,值是搜索类型,包括

  • left_text:匹配列值的左侧
  • right_text:匹配列值的右侧
  • equals:搜索的文本应该等于列值
  • full_text:搜索的文本应该位于搜索的列中的任何位置。

实际应用

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

use Vluzrmos\SimpleSearchable\Eloquent\SimpleSearchableTrait;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
	use Authenticatable, CanResetPassword, SimpleSearchableTrait;

	protected $searchable = [
		'name' => 'full_text',
		'posts.title' => 'full_text',
		// query deeply into your relations, that relations should exists on the respective models.
		'posts.comments.owner.name' => 'full_text'
	];

	public function posts()
	{
		return $this->hasMany(Post::class);
	}
}

在你的控制器或其他任何地方

$users = User::search('Jonh')->get();

// or replace the default searchable fields:

$users = User::search('Jonh', ['name' => 'full_text'])->get();

注意:搜索方法是一个范围,所以你需要使用查询构建器方法如 getall 来执行搜索并获取结果集合。