ibrostudio / laravel-teamable
为 Eloquent 模型添加团队属性
Requires
- php: ^8.2
- ibrostudio/laravel-data-repository: ^1.0
- illuminate/contracts: ^11.0
- michael-rubel/laravel-value-objects: ^7.0
- spatie/laravel-package-tools: ^1.14.0
- spatie/laravel-sluggable: ^3.5
Requires (Dev)
- larastan/larastan: ^2.0.1
- laravel/pint: ^1.0
- nunomaduro/collision: ^8.0
- orchestra/testbench: ^9.0
- pestphp/pest: ^2.20
- pestphp/pest-plugin-arch: ^2.0
- pestphp/pest-plugin-laravel: ^2.0
- phpstan/extension-installer: ^1.1
- phpstan/phpstan-deprecation-rules: ^1.0
- phpstan/phpstan-phpunit: ^1.0
README
为 Eloquent 模型添加团队属性。
安装
通过 composer 安装此包
composer require ibrostudio/laravel-teamable
然后运行安装程序
php artisan data-repository:install
用法
配置
将特质 IBroStudio\Teamable\Concerns\IsTeamable
和接口 \IBroStudio\Teamable\Contracts\Teamable
添加到必须为团队的 Eloquent 模型中。
您可以根据需要定义许多模型作为团队。
namespace App\Models; use IBroStudio\Teamable\Concerns\IsTeamable; use Illuminate\Database\Eloquent\Model; class Company extends Model implements \IBroStudio\Teamable\Contracts\Teamable { use IsTeamable; }
将特质 IBroStudio\Teamable\Concerns\HasTeams
添加到将定义团队成员的 Eloquent 模型中。
namespace App\Models; use IBroStudio\Teamable\Concerns\HasTeams; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use HasTeams; }
创建团队
当您创建具有 IBroStudio\Teamable\Concerns\IsTeamable
特质的模型时,会自动创建一个 IBroStudio\Teamable\Models\Team
模型,使用在 teamable.php
配置文件中定义的模型属性作为团队名称。
默认使用的模型属性是 name
。如果您的模型没有名称,您可以在 teamable.php
配置文件中设置另一个属性以使用。
'model_name_attribute' => [ 'default' => 'name', Company::class => 'company_name' ],
您可以通过将 teamable.php
配置文件中的 auto.create
设置为 false 来禁用自动创建团队。
$company = Company::create([ 'name' => 'iBroStudio', ]); $company->team; // This give access to the team model through a MorphOne relationship
将团队添加到现有模型
$company->createTeam(); $company->team; // This give access to the team model
向团队添加成员
$user->attachTeam($company->team);
用户可以是多个团队的成员,并且可以是不同类型的团队
$user->attachTeam($company_1->team); $user->attachTeam($company_2->team); $department = Department::create([ 'name' => 'Development', ]); $user->attachTeam($department->team);
当前团队 ID
为了方便使用,每个团队类型的数据库中都会存储一个 当前团队 ID 属性。
当您向团队添加成员时,值会被设置为该团队的 ID。
您可以使用 getCurrentTeamId(TeamType $teamType)
方法检索值。
$user->getCurrentTeamId(TeamType::make(Company::class)); // or $user->getCurrentTeamId($company_1->team->type); $user->getCurrentTeamId(TeamType::make(Department::class));
要更改当前团队 ID,请使用 switchToTeam
方法
$user->switchToTeam($company_2->team);
从团队中移除成员
$user->detachTeam($company->team);
删除团队
当您删除具有 IBroStudio\Teamable\Concerns\IsTeamable
特质的模型时,团队模型会自动删除。
您可以通过将 teamable.php
配置文件中的 auto.delete
设置为 false 来禁用自动删除团队。
测试
composer test
变更日志
请参阅 CHANGELOG 以获取有关最近更改的更多信息。
许可证
MIT 许可证 (MIT)。请参阅 许可证文件 以获取更多信息。