studio-net/laravel-scoresearch

该软件包最新版本(dev-master)没有可用的许可证信息。

dev-master 2017-11-30 14:41 UTC

This package is auto-updated.

Last update: 2024-09-25 06:12:15 UTC


README

欢迎回家!让我为您介绍这个软件包。事实上,这个软件包处理两个重要的事情

  • 语法文件(MySQL和PostgreSQL);
  • 一个简单的特质;

ScoreSearch允许您通过实现所提供特质的新方式,基于评分搜索任何实体,以获取更相关的行。目前,我只测试了PostgreSQL。如果有人需要,可能会实现其他数据库引擎。

Latest Stable Version Latest Unstable Version Total Downloads Monthly Downloads Daily Downloads License Build Status

安装

只需要最基础的安装。

composer require 'studio-net/laravel-scoresearch @dev'

用法

将提供的特质添加到所需的Eloquent模型中,并提供一个简单的searchable受保护变量来列出每个元素的权重。如果未指定列,则默认权重为1。

# app/User.php

namespace App;

use Illuminate\Database\Eloquent\Model;
use StudioNet\ScoreSearch\Searchable;

/**
 * User
 *
 * @see Model
 */
class User extends Model {
	use Searchable;

	/** @var array $searchable */
	protected $searchable = [
		'columns' => [
			'username' => 10,
			'age'      => 5,
			'email'    => 15,
		]
	];
}

现在,您可以通过使用search作用域,将比较的数组作为第一个参数传递,简单地返回一个搜索。

$users = User::search([
		'username' => ['or' => ['cyril', 'studio-net']],
		'email'    => ['or' => ['%@studio-net.fr', '%@studio-net.com'], '%boss'],
		'age'      => '(gt) 20',
	])

	->where('active', true)
	->get();
select * from (
	select users.*, (
		(case when (((username = 'cyril') OR (username = 'studio-net'))) then 10 else 0 end) +
		(case when (((email ilike '%@studio-net.fr') OR (email ilike '%@studio-net.com')) AND (email ilike '%boss')) then 15 else 0 end) +
		(case when (age > 20) then 5 then 0 end)
	) as score from users
) as users where score >= ? and active is true order by score desc

规范

为了使用操作符,您可以参考下面的示例。否则,这是默认的语法:(operator) text,除了%=不需要处理操作符情况,只需字符串本身即可,例如cyril将生成= cyrilcyril%将生成ilike 'cyril%'

关系

您可以在您的$searchable变量实例中指定一个可以处理表名的joins数组。您可以通过设置子集来指定on

	protected $searchable = [
		'joins'   => ['posts'],
		'joins'   => ['posts' => ['posts.id', 'users.id']],

		'columns' => [
			'posts.title' => 5,
			'user.login'  => 10
		]
	];

	// Fetch users with related posts
	User::search(['user.login' => 'cyril', 'posts.title' => '%toto%'])->with('posts')->get();

Eloquent

您可以使用Eloquent提供的任何方法。由于该软件包使用子查询,您可以轻松地执行类似以下查询:

User::where('role', 'admin')
	->search(['email' => '%@studio-net.fr'])
	->with('posts')
	->paginate(20);

贡献

感谢您考虑为这个Laravel软件包做出贡献。您可以通过创建问题和拉取请求来改进这个强大的软件包。

许可证

此Laravel软件包是开源软件,受MIT许可证许可。