mayoz / laravel-categorizable
Laravel的多态分类器
1.0.1
2017-09-11 22:18 UTC
Requires
- php: ^7.0
- illuminate/database: ~5.4|~5.5
- illuminate/support: ~5.4|~5.5
Requires (Dev)
- orchestra/testbench: ^3.4
- phpunit/phpunit: ^6.0
This package is auto-updated.
Last update: 2024-08-27 23:14:37 UTC
README
轻松地在Laravel 5中为Eloquent模型添加分类功能。
安装
您可以通过composer安装此包
composer require mayoz/laravel-categorizable
在配置文件config/app.php
中注册服务提供者
'providers' => [ ... Mayoz\Categorizable\CategorizableServiceProvider::class, ... ];
您可以使用以下命令发布迁移
php artisan vendor:publish --provider="Mayoz\Categorizable\CategorizableServiceProvider" --tag="migrations"
迁移已发布,您可以创建categories
和categorizable
表。您可以自由添加所需的新字段。之后,运行迁移
php artisan migrate
使用
假设,您有如下Post
模型
<?php namespace App; use Mayoz\Categorizable\Categorizable; use Illuminate\Database\Eloquent\Model; class Post extends Model { use Categorizable; }
为Post
模型关联新的分类
$post = Post::find(1); $post->categorize([1, 2, 3, 4, 5]); return $post;
现在,post
模型关联了分类ID为1
、2
、3
、4
和5
。
为Post
模型移除现有的分类关联
$post = Post::find(1); $post->uncategorize([3, 5]); return $post;
post
模型关联了分类ID为1
、2
和4
。
重新排列Post
模型的分类关系
$post = Post::find(1); $post->recategorize([1, 5]); return $post;
post
模型关联了分类ID为1
和5
。
扩展
建议您始终扩展Category
模型来直接定义关系。创建您自己的Category
模型
<?php namespace App; use Mayoz\Categorizable\Category as BaseCategory; class Category extends BaseCategory { /** * Get all posts for the relation. * * @return \Illuminate\Database\Eloquent\Relations\MorphedByMany */ public function posts() { return $this->categorized(Post::class); } }
发布包配置
php artisan vendor:publish --provider="Mayoz\Categorizable\CategorizableServiceProvider" --tag="config"
这是已发布配置文件的内容
<?php return [ /* |-------------------------------------------------------------------------- | Model Namespace |-------------------------------------------------------------------------- | | Change these values when you need to extend the default category model | or if the user model needs to be served in a different namespace. | */ 'category' => App\Category::class, ];
这就完成了。现在让我们用分类来玩关系查询。
/** * Respond the post * * @param \App\Category $category * @return \Illuminate\Http\Response */ public function index(Category $category) { return $category->posts()->paginate(10); }
如果我们没有扩展Category
模型,就必须使用;
/** * Respond the post * * @param \App\Category $category * @return \Illuminate\Http\Response */ public function index(Category $category) { return $category->categorize(Post::class)->paginate(10); }
许可
本软件包采用MIT许可(MIT)许可。