jutia-dev/laravel-category

将Laravel模型关联到分类/分类们

0.0.1-alpha 2021-11-16 23:18 UTC

This package is auto-updated.

Last update: 2024-09-17 06:07:08 UTC


README

php artisan vendor:publish --provider="JutiaDev\Category\CategoryServiceProvider"

关系

  • 所有使用hasCategories特质的所有模型将能够访问以下关系$model->categories,它将获取与该$model关联的所有分类

  • 所有使用hasCategory特质的所有模型将能够访问以下关系$model->category,它将获取与该$model关联的分类

  • 您可以通过$category->{$relationshipName}获取与一个$category关联的所有模型,其中$relationshipName将默认从模型类推导出来

    • 例如,从Product模型推导出的$relationshipName将是products,因此您可以使用$category->products来访问它,您可以使用辅助函数deduce_relationship_name_from_model(\App\Models\Product::class)获取模型的relationName
    • 您可以通过在hasCategorieshasCategory特质使用的模型上添加此变量(protected string $relationshipName = 'customProducts';)来自定义relationshipName

迁移

何时重新运行分类包的迁移使用php artisan migrate_category:refresh

  • 添加使用hasCategoryhasCategories特质的模型
  • 将使用hasCategory特质的模型特质更改为hasCategories或相反
  • 更改使用hasCategory特质的模型上cascadeDelete的值
  • 从使用其中一个的模型中删除hasCategoryhasCategories

1 - 关于cascadeDelete的说明

  • 默认情况下,使用hasCategory特质的模型上cascadeDelete将为false,因此当关联的分类被删除时,外键将被设置为null。如果您希望模型也被删除,则需要在使用hasCategory特质的模型上设置此变量:protected bool $cascadeDelete = true;

2 - 重新运行迁移的影响

  • 如果任何Eloquent模型开始使用hasCategories特质且表不存在,则将创建Categorizable表

  • 如果没有任何模型使用hasCategories特质且表已存在,则将删除Categorizable表

  • 如果模型从hasCategories特质切换到hasCategory特质,则将在模型中添加引用分类ID的新列(外键)。但是,如果未删除Categorizable表(检查上述点),则数据将保留在Categorizable表中

  • 如果使用hasCategories特质的模型不再使用任何分类特质,则将删除引用category_id的外键列

  • 如果使用hasCategories特质的模型切换到hasCategories特质,则将删除引用category_id的外键列,但如果Categorizable表尚未创建,则所有数据将迁移到Categorizable表。

3 - php artisan migrate_category:refresh的作用

  • php artisan migrate:refresh --path=/database/migrations/2021_11_13_000001_create_categorizable_table.php
  • php artisan migrate:refresh --path=/database/migrations/2021_11_13_000002_add_categories_foreign_key_to_related_models.php

资源