mayoz / laravel-categorizable

Laravel的多态分类器

1.0.1 2017-09-11 22:18 UTC

This package is auto-updated.

Last update: 2024-08-27 23:14:37 UTC


README

Latest Version on Packagist Software License Build Status StyleCI

轻松地在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"

迁移已发布,您可以创建categoriescategorizable表。您可以自由添加所需的新字段。之后,运行迁移

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为12345

Post模型移除现有的分类关联

$post = Post::find(1);

$post->uncategorize([3, 5]);

return $post;

post模型关联了分类ID为124

重新排列Post模型的分类关系

$post = Post::find(1);

$post->recategorize([1, 5]);

return $post;

post模型关联了分类ID为15

扩展

建议您始终扩展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)许可。