️ 该软件包将被弃用,取而代之的是:https://github.com/open-southeners/laravel-model-status
Eloquent 模型的 Laravel 代码类型状态。
您可以通过 Composer 安装该软件包:
composer require skore-labs/laravel-status
然后您需要发布包配置和迁移,以便您可以修改和/或迁移新的状态表:
php artisan vendor:publish --provider="SkoreLabsLaravelStatusServiceProvider"
通过添加SkoreLabsLaravelStatusTraitsHasStatuses
和接口SkoreLabsLaravelStatusContractsStatusable
来向模型添加状态,以便它可以传递一些预定义的事件(见上文),下面是一个示例:
<?php
namespace App ;
use Illuminate Database Eloquent Model ;
use SkoreLabs LaravelStatus Contracts Statusable ;
use SkoreLabs LaravelStatus Traits HasStatuses ;
class Post extends Model implements Statusable
{
use HasStatuses;
// Your model logic here...
}
自定义枚举以进行状态检查(使用spatie/enum包,检查其文档):
/**
* Get the statuses enum used for some utilities.
*
* @return string|SpatieEnumEnum
*/
public static function statusesClass ()
{
return App Statuses PostStatuses::class;
}
注意:这不是必需的,仅当您没有将所有模型状态枚举类作为ModelStatus
存储在AppEnums
中时。
注意:所有方法的状态名称都不区分大小写。
检查模型是否有状态。
注意:它返回当前匹配的状态名称。
// Post has status Published
$ post -> hasStatus ( ' published ' );
// Post has status Published or Was Published
$ post -> hasStatus ([ ' published ' , ' was published ' ]);
仅当先前状态与键匹配时才设置状态或改变状态。
// Set post status to Was Published
$ post -> setStatus ( ' was published ' );
// Change if post has status Published to Was Published.
$ post -> setStatus ([ ' published ' => ' was published ' ]);
您还可以使用该属性来设置状态:
$ post -> status = ' was published ' ;
// Better use status method for this
if ( $ post -> hasStatus ( ' published ' )) {
$ post -> status = ' was published ' ;
}
// When save it check and attach the status
$ post -> save ();
您也可以使用setStatusWhen
方法执行相同的操作,如上面的setStatus
示例。
// Change if post has status Published to Was Published.
$ post -> setStatusWhen ( ' published ' , ' was published ' );
如果提供了参数,则它充当 hasStatus 的别名。
如果提供了关联数组,则它充当 setStatus 的别名。
否则,它只会将关系检索为$post->status
或$post->status()->first()
您还可以按范围过滤:
Post:: status ( ' published ' );
Post:: where ( ' user_id ' , Auth:: id ())-> status ( ' published ' );
获取所有可能的模型状态。
Post:: statuses ();
// You can use Status model as well
Status:: getFrom (Post::class);
// Also specify value to return like '->value('id')'
Status:: getFrom (Post::class, ' id ' );
// Or return the object with columns like '->first(['id', 'name'])'
Status:: getFrom (Post::class, [ ' id ' , ' name ' ]);
获取模型的默认状态。
// Default status for post is Published, so it returns Published
Post:: getDefaultStatus ();
// You can use Status model query scope as well
Status:: query ()-> defaultFrom (Post::class)-> first ();
这个以及我们所有的 Laravel 包都尽可能遵循 Laravel 的 LTS 支持。
了解更多:https://laravel.com/docs/master/releases#support-policy