robotsinside/laravel-categorise-it

一个用于分类Laravel Eloquent模型的包。

这个包的官方仓库似乎已经不存在,因此该包已被冻结。

0.0.3 2020-06-06 01:44 UTC

This package is auto-updated.

Last update: 2020-12-06 02:53:49 UTC


README

Latest Version on Packagist Total Downloads License: MIT

这是一个简单的用于在Laravel中分类Eloquent模型的包。此包是Laravel Tag It(点击查看)的兄弟包,后者可以用于标记Eloquent模型。API几乎与此相同。

安装

  1. 使用Composer安装
composer require robotsinside/laravel-categorise-it
  1. 可选地,在config/app.php中注册服务提供者
/*
* Package Service Providers...
*/
\RobotsInside\CategoriseIt\CategoriseItServiceProvider::class,

自动发现已启用,因此可以跳过此步骤。

  1. 发布迁移
php artisan vendor:publish --provider="RobotsInside\CategoriseIt\CategoriseItServiceProvider" --tag="migrations"
  1. 迁移数据库。这将创建两个新表:categoriescategorisables
php artisan migrate

使用方法

在模型中使用RobotsInside\CategoriseIt\Categorisable特质。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use RobotsInside\CategoriseIt\Categorisable;

class Post extends Model
{
    use Categorisable;
}

现在您可以开始分类模型了。模型可以通过传递一个整数、整数数组、模型实例或模型集合来进行分类。

<?php

use App\Post;
use Illuminate\Support\Facades\Route;
use RobotsInside\CategoriseIt\Models\Category;

Route::get('/', function () {

    // Retrieve a new or existing category
    $category1 = (new Category())->resolve('Category 1');
    $category2 = (new Category())->resolve('Category 2');

    // Or, retrieve a collection of new or existing categories
    $categories = (new Category())->resolveAll(['Category 1', 'Category 2', 'Category 3'])

    $post = new Post();
    $post->title = 'My blog';
    $post->save();

    $post->categorise($category1);
    // Or
    $post->categorise(['category-1']);
    // Or
    $post->categorise([1, 2]);
    // Or
    $post->categorise(Category::get());
});

取消分类模型同样简单。

<?php

use App\Post;
use Illuminate\Support\Facades\Route;
use RobotsInside\CategoriseIt\Models\Category;

Route::get('/', function () {

    $category1 = Category::find(1);

    $post = Post::where('title', 'My blog')->first();

    $post->uncategorise($category1);
    // Or
    $post->uncategorise(['category-1']);
    // Or
    $post->uncategorise([1, 2]);
    // Or
    $post->uncategorise(Category::get());
    // Or
    $post->uncategorise(); // remove all categories
});

作用域

每次使用RobotsInside\CategoriseIt\Models\Category时,categories表中的count列都会增加。当删除一个分类时,计数会递减,直到为零。

此包提供了一些预定义的作用域,以简化对count列的查询,例如>=><=<约束,例如:

  • Category::usedGte(1);
  • Category::usedGt(2);
  • Category::usedLte(3);
  • Category::usedLt(4);

RobotsInside\CategoriseIt\Models\Categorisable模型包含一个作用域,用于限制在给定时间框架内创建的记录。此作用域支持人类可读的值,包括daysmonthsyears,以及单数和复数形式,例如:

  • Categorisable::categorisedWithin('7 days');
  • Categorisable::categorisedWithin('1 month');
  • Categorisable::categorisedWithin('2 years');

安全

如果您发现任何安全相关的问题,请通过电子邮件robertfrancken@gmail.com而不是使用问题跟踪器。

致谢

许可

MIT许可(MIT)。请参阅许可文件以获取更多信息。