首页 > 解决方案 > Laravel 5.6 自定义 id 每天都有 mutator 重置计数器

问题描述

我使用 mutator 为我的记录创建一个自定义 id,使其看起来像这样:

yyyy-mm-dd-{序列}

序列看起来像这样

00001
00002
...

所以它是 5 位数字,只是一个计数器。

我有2个问题

1)我不知道如何在我的 mutator 中创建一个计数器,我可以做一个 for 循环,但我现在不知道如何制作一个在明天重置的无限​​循环。

2)老实说,我不知道如何让它每天重置。

我的突变体:

public function setFunctionalIdAttribute($id)
{
    $date = Carbon::now()->format("Y-m-d");

    // I take an extremely large number here because there will never be so much records in 1 day.
    for ($counter = 0; $counter <= 100000000000; $counter++) {
        $counter = str_pad($counter, 5, '0', STR_PAD_LEFT);
    }

    $today = Carbon::today();
    $tomorrow = Carbon::tomorrow();

    if ($today = $tomorrow) {
        $counter = 0;
    }

    $this->attributes['functional_id'] = $date . "-" . $counter;
}

标签: phplaravel-5

解决方案


很难说,但是,以最好的方式,你的计数器循环没有任何意义,我很抱歉!我建议完全摆脱它,或者至少阅读str_pad.

您还有一个条件语句来检查“今天是明天”。这对我来说是一个很大的危险信号,一般来说,逻辑是不正确的。

让我们考虑一个替代方案。您实际上是在计算一天中的记录数,以将其用作 ID。我建议采用类似于此的方法:

public function setFunctionalIdAttribute()
{
  // 1. Count how many records there are from today
  // 2. Make an ID that is this number + 1
  // 3. If need be, string pad left with 0's
}

1. 数一数今天有多少条记录

Laravel 有一个方便的whereDate功能——来自文档(搜索whereDate

$count = DB::table('users')
                ->whereDate('created_at', Carbon::today()->toDateString())
                ->count();

因此,如果我们今天制作了 3 条记录,那$count就是 3 条。

2.制作一个ID就是这个数字+1

$count ++;

3.如果需要,字符串填充左有0

str_pad 上的 PHP 文档非常糟糕,让我们只介绍基础知识:

str_pad($input, $length, $pad_string, $pad_type);
  • $input是您要填充的字符串
  • $length是字符串的最终长度(这就是为什么你的 for 循环是完全没有必要的)
  • $pad_string如果字符串长度小于$length,用这个填充剩余空间
  • $pad_type 正如你正确的那样,是一个可选的标志来填充左边

$input$count,你$length是 5,从你的例子来看,$pad_string是“0”,我们保持PAD_LEFT.

$id = str_pad($count, 5, "0", PAD_LEFT)

我不记得如何通过 mutator 设置属性,所以只需复制您的示例(我希望这是正确的!)我们得到:

public function setFunctionalIdAttribute()
{
  $count = DB::table('users') // Remember to change this to the correct table name
    ->whereDate('created_at', Carbon::today()->toDateString())
    ->count();
  $count ++;
  $id = str_pad($count, 5, PAD_LEFT)
  $this->attributes['functional_id'] = $id;
}

请记住仅在创建时执行此操作,因为我们不想在每次保存时增加此 ID。


推荐阅读