codewithtony/laravel-active-attribute

Laravel Active Attribute

1.0 2018-11-16 13:36 UTC

This package is not auto-updated.

Last update: 2024-09-15 05:54:57 UTC


README

Laravel Active Attribute 为 Eloquent 模型添加了 withInactiveonlyInactive 功能。

这可以用来自动隐藏非活动记录,除非有其他需求。可能使用 软删除 是更好的解决方案,但可能有一些原因让你想使用活动字段。

这也可以作为如何使用 Laravel 中的 Scopes 和 Macros 来在更高层次上操作查询的一个好例子。

安装

composer require codewithtony/laravel-active-attribute

用法

HasActiveAttribute 添加到任何具有 ->active 字段的 Eloquent 模型,该字段是 1/0 的布尔值

class Thing 
{
    Use HasActiveAttribute;
    ...
}

之后,你可以这样使用它

Thing::all(); // only records where $model->active = 1
// or
Thing::withInactive()->all(); // records where $model->active = 1 OR 0
// or
Thing::onlyInactive()->all(); // only records where $model->active = 0

自定义活动字段

默认情况下,active 是这个将检查的默认字段,要自定义它,可以设置常量 ACTIVE。例如,如果字段名为 is_active

class Thing 
{
    const ACTIVE = 'is_active';
    Use HasActiveAttribute;
    ...
}