robotsinside/laravel-categories

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

1.2.1 2022-10-16 07:23 UTC

This package is auto-updated.

Last update: 2024-09-16 11:56:50 UTC


README

Latest Version on Packagist Total Downloads CI License: MIT

这是一个用于在 Laravel 中对 Eloquent 模型进行分类的简单包。此包与 Laravel Tags 是兄弟包,后者可用于对 Eloquent 模型进行标记。API 与此相同。

目录

安装

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

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

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

用法

在您的模型中使用 RobotsInside\Categories\Categorisable 特性。

<?php

namespace App;

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

class Post extends Model
{
    use Categorisable;
}

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

<?php

use App\Post;
use Illuminate\Support\Facades\Route;
use RobotsInside\Categories\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\Categories\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\Categories\Models\Category 时,categories 表中的 count 列都会增加。当删除分类时,计数会递减直到为零。

此包附带了一些预定义的作用域,以便更容易对 count 列进行查询,例如 >=><=< 约束,例如

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

RobotsInside\Categories\Models\Categorisable 模型包含一个作用域,用于约束在给定时间范围内创建的记录。此作用域支持人类可读的值,包括单数和复数格式的 daysmonthsyears,例如

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

安全性

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

鸣谢

咖啡时间

为 ☕☕☕ 工作

Buy Me A Coffee

许可证

MIT 许可证(MIT)。有关更多信息,请参阅 许可证文件