robotsinside / laravel-tag-it
用于标记 Laravel Eloquent 模型的包。
此包的规范存储库似乎已消失,因此该包已被冻结。
1.2.1
2020-06-04 04:33 UTC
Requires
- php: >=7.0.0
- illuminate/database: >=5.0
- illuminate/support: >=5.0
Requires (Dev)
- orchestra/testbench: ^5.1
- phpunit/phpunit: ^9.1
This package is auto-updated.
Last update: 2020-12-03 04:06:57 UTC
README
Laravel 的 Eloquent 标记包。此包与 Laravel Categorise It 是兄弟关系,后者可以用于对 Eloquent 模型进行分类。API 几乎与这个相同。
安装
- 使用 Composer 安装
composer require robotsinside/laravel-tag-it
- 在
config/app.php
中注册服务提供者
/* * Package Service Providers... */ \RobotsInside\TagIt\TagItServiceProvider::class,
自动发现已启用,因此可以跳过此步骤。
- 发布迁移
php artisan vendor:publish --provider="RobotsInside\TagIt\TagItServiceProvider" --tag="migrations"
- 迁移数据库。这将创建两个新表:
tags
和taggables
php artisan migrate
通用用法
在你的模型中使用 RobotsInside\TagIt\Taggable
特性。
<?php namespace App; use Illuminate\Database\Eloquent\Model; use RobotsInside\TagIt\Taggable; class Post extends Model { use Taggable; }
现在你可以开始标记了。可以通过传递整数、整数数组、模型实例或模型集合来标记模型。
<?php use App\Post; use Illuminate\Support\Facades\Route; use RobotsInside\TagIt\Models\Tag; Route::get('/', function () { $tag1 = (new Tag())->make('Tag 1'); $tag2 = (new Tag())->make('Tag 2'); $post = new Post(); $post->title = 'My blog'; $post->save(); $post->tag($tag1); // Or $post->tag(['tag-1']); // Or $post->tag([1, 2]); // Or $post->tag(Tag::get()); });
取消标记模型同样简单。
<?php use App\Post; use Illuminate\Support\Facades\Route; use RobotsInside\TagIt\Models\Tag; Route::get('/', function () { $tag1 = Tag::find(1); $post = Post::where('title', 'My blog')->first(); $post->untag($tag1); // Or $post->untag(['tag-1']); // Or $post->untag([1, 2]); // Or $post->untag(Tag::get()); // Or $post->untag(); // remove all tags });
作用域
每次使用 RobotsInside\TagIt\Models\Tag
时,都会将 tags
表中的 count
列增加。当移除标签时,计数会递减,直到为零。
此包提供了一些预定义的作用域,使对 count
列的查询更容易,包括 >=
、>
、<=
和 <
约束,例如
Tag::usedGte(1);
Tag::usedGt(2);
Tag::usedLte(3);
Tag::usedLt(4);
此外,还提供了一个对 Taggable
模型的作用域,以限制在给定时间范围内创建的记录。此作用域支持人类可读的值,包括单数和复数格式的 days
、months
和 years
,例如
Taggable::taggedWithin('7 days');
Taggable::taggedWithin('1 month');
Taggable::taggedWithin('2 years');
致谢
许可
MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件。