leko-team / laravel-active
为使用 Eloquent 模型激活实体提供现成的解决方案
1.0.0
2023-10-23 15:29 UTC
Requires (Dev)
- orchestra/testbench: ^8.13.0
- phpunit/phpunit: ^10.4
README
此包可以激活实体与 Eloquent 模型。它提供了一个简单的 API 以进行操作。
安装
可以通过 Composer 安装此库
composer require leko-team/laravel-active
配置
要能够激活 Eloquent 实体,您需要
$table->boolean('is_active')->default(false)->index()->comment('活动标志'); $table->timestamp('start_at')->nullable()->index()->comment('活动开始时间戳'); $table->timestamp('end_at')->nullable()->index()->comment('活动结束时间戳');
- 添加包含列:
is_active
、start_at
、end_at
的迁移 - 或分配:
static::IS_ACTIVE
、static::START_AT
、static::END_AT
常量,以使用您想要的列名。
php artisan make:migration add_active_columns_in_`your-table`_table
public function up(): void { Schema::table('your-table', function (Blueprint $table) { $table->boolean('is_active')->default(true)->index(); $table->timestamp('start_at')->nullable()->index(); $table->timestamp('end_at')->nullable()->index(); }); } public function down(): void { Schema::table('your-table', function (Blueprint $table) { $table->dropColumn('end_at'); $table->dropColumn('start_at'); $table->dropColumn('is_active'); }); }
如果您表中已有现有记录,您可能想要更新它们。
- 将 trait
ActivityTrait
添加到您的模型中。
use ActivityTrait;
示例
基础
激活实体
$review = Review::first(); $review->activate();
停用实体
$review = Review::first(); $review->deactivate();
作用域
默认情况下,从活动实体返回只有活动的记录,条件如下: 实体为真且 start_at 为 NULL 或 <= 当前时间戳 ('2023-10-23 13:52:37') 且 end_at 为 NULL 或 end_at >= 当前时间戳 ('2023-10-23 13:52:37')
。您可以通过应用作用域来更改此设置。
- withInactive
$review = Review::withInactive()->get();
返回所有记录。
致谢
- 非常感谢 Laravel Package 在构建包时提供的逐步指南。
- Oleg Kolzhanov 在逻辑上的帮助。
许可证
MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件。