Laravel 9枚举条件

发布于 2025-02-03 10:13:32 字数 357 浏览 3 评论 0原文

我创建一个枚举,我添加了一个条件:

<?php

declare(strict_types=1);

namespace App\Enums;

use App\Models\collections;

enum ServiceColections : string {


    case POS = (isset(collections::first()))? 'POS' : '';

}

如果数据库中有项目(表集合),则条件是以下条件,因此请创建Case POS,但是如果它们不存在,则不会创建。

目前,我遇到此错误:枚举案例值必须是编译时间评估

为什么它不起作用?

I'm create one enum, and I added one condition:

<?php

declare(strict_types=1);

namespace App\Enums;

use App\Models\collections;

enum ServiceColections : string {


    case POS = (isset(collections::first()))? 'POS' : '';

}

the condition is the following if there are items in the database(table collections), so create case POS, but if they don't exist don't create.

currently I'm having this error: Enum case value must be compile-time evaluatable

why it dont work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

献世佛 2025-02-10 10:13:32

正如其自我所说的错误时,这在编译时行不通。

我们可以做的是,添加枚举方法:

use App\Models\collections;

enum ServiceColections 
{
    case POS;

    public function collection(): string // name the function of your choice
    {
        return match($this) 
        {
            self::POS => collections::first() ? 'POS' : '',
        };
    }
}

可以像这样使用的方法:

\App\Enums\ServiceColections::POS->collection();

As the error its self say, this will not work at the time of compiling.

What we can do is, add enum method:

use App\Models\collections;

enum ServiceColections 
{
    case POS;

    public function collection(): string // name the function of your choice
    {
        return match($this) 
        {
            self::POS => collections::first() ? 'POS' : '',
        };
    }
}

Methods can be used like so:

\App\Enums\ServiceColections::POS->collection();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文