beaumind/searchable

一个简单的php trait,用于laravel在模型和相关模型中搜索

1.0.1 2017-01-04 08:00 UTC

This package is auto-updated.

Last update: 2024-09-19 16:38:34 UTC


README

一个简单的php trait,用于laravel >= 5.0,在模型和相关模型中搜索

安装

简单运行Composer require命令。

composer require beaumind/searchable

使用

将特性添加到您的模型和搜索规则中。

use Beaumind\Searchable\Searchable;

class Post extends \Eloquent
{
    use Searchable;

    /**
     * Searchable columns.
     *
     * @var array
     */
    public $searchable_fields = [
      title,
      body,
      user.name,
      uesr.email
    ];


    public function user()
    {
        return $this->belongsTo('User');
    }

}

现在您可以在模型中进行搜索。

// Simple search
$posts = Post::search($query)->get();

// Search and get relations
// It will not get the relations if you don't do this
$posts = Post::search($query)
            ->with('user')
            ->get();

搜索分页

与laravel默认查询一样简单

// Search with relations and paginate
$posts = Post::search($query)
            ->with('user')
            ->paginate(20);

混合查询

搜索方法与任何Eloquent方法兼容。您可以进行如下操作

// Search only active posts
$posts = Post::where('status', 'active')
            ->search($query)
            ->paginate(20);