bolv88/laravel-tagging

使用 PHP 特性扩展 Laravel Eloquent 模型以允许标签。模型可以被标记为可标签化。

2.2.3 2017-04-13 09:43 UTC

README

Latest Stable Version Total Downloads License Build Status

此包不旨在以任何方式处理 JavaScript 或 HTML。此包仅处理数据库存储和读写。

标签中可使用的字符没有实际限制。它使用 slug 转换来确定两个标签是否相同("sugar-free" 和 "Sugar Free" 将被视为相同的标签)。标签显示名称将经过 Str::title() 处理。

Laravel/Lumen 5 文档
Laravel 4 文档

Composer 安装(针对 Laravel 5.3/Lumen 5)

composer require rtconner/laravel-tagging "~2.2"

安装并运行迁移

服务提供者不会在每次页面加载时加载,因此它不会减慢您的应用程序。

'providers' => array(
	\Conner\Tagging\Providers\TaggingServiceProvider::class,
);
php artisan vendor:publish --provider="Conner\Tagging\Providers\TaggingServiceProvider"
php artisan migrate
Lumen 5 安装

Lumen 没有vendor:publish 命令,因此您需要将提供的迁移和配置文件创建或复制到相应的目录中。

在 app\bootstrap\app.php 中

// Add this line in your config section
$app->configure('tagging');
// Add this line in your service provider section
$app->register(Conner\Tagging\Providers\LumenTaggingServiceProvider::class);

完成这两个步骤后,您可以使用您首选的设置编辑 config/tagging.php。

设置您的模型

class Article extends \Illuminate\Database\Eloquent\Model {
	use \Conner\Tagging\Taggable;
}

快速示例用法

$article = Article::with('tagged')->first(); // eager load

foreach($article->tags as $tag) {
	echo $tag->name . ' with url slug of ' . $tag->slug;
}

$article->tag('Gardening'); // attach the tag

$article->untag('Cooking'); // remove Cooking tag
$article->untag(); // remove all tags

$article->retag(array('Fruit', 'Fish')); // delete current tags and save new tags

$article->tagNames(); // get array of related tag names	

Article::withAnyTag(['Gardening','Cooking'])->get(); // fetch articles with any tag listed

Article::withAllTags(['Gardening', 'Cooking'])->get(); // only fetch articles with all the tags

Conner\Tagging\Model\Tag::where('count', '>', 2)->get(); // return all tags used more than twice

Article::existingTags(); // return collection of all existing tags on any articles

更多示例请参阅文档

标签组

您可以使用以下 artisan 命令创建组

php artisan tagging:create-group MyTagGroup

为标签设置标签组

$tag->setGroup('MyTagGroup');

获取某个组中的所有标签

Tag::inGroup('MyTagGroup')->get()

检查标签是否在组中

$tag->isInGroup('MyTagGroup');

配置

查看 config/tagging.php 以获取配置选项

进一步文档

查看 docs/ 文件夹以获取更多文档

Laravel 4 升级到 5

此库将完整的模型类名存储到数据库中。当您升级 Laravel 并为您的模型添加命名空间时,您需要更新数据库中存储的记录。或者,您可以在您的模型类上覆盖 Model::$morphClass 以匹配数据库中存储的字符串。

致谢

进一步阅读