php - 自动为 laravel 模型中的字段赋值

我正在使用 laravel,在我的一个模型中,我需要在每次创建记录时自动将值分配给一个字段(日期类型),因为我刚开始使用 laravel,我不这样做,因为我尝试使用突变器:

public function setApprovedDateAttribute($date)
{
    $this->attributes['approved_date'] = Carbon::now()->format('Y-m-d');
}

但这对我不起作用,因为我认为增变器正如它的名字所说的那样改变了我为这个字段发送的值,在我的例子中我需要在每次创建新记录时自动添加一个, 那么我该怎么做呢?

最佳答案

正如@apokryfos 在评论中提到的,最好是在创建事件时执行此操作。 在这里你应该做什么,假设你的表是 subscriptions 字段 subscriptions.approved_date 和模型是 Subscription,这是非常干净的方式你可以做些什么来获得发布的结果:

1. php artisan make:observer SubscriptionObserver --model=Subscription

<?php

namespace App\Observers;

use App\Subscription;
use Carbon\Carbon;

class SubscriptionObserver
{
    /**
     * Handle the subscription "creating" event.
     *
     * @param Subscription $subscription
     * @return void
     */
    public function creating(Subscription $subscription)
    {
        $subscription->approved_date = Carbon::now()->format('Y-m-d');
    }
}

注意:我添加了 creating() 方法,它默认不存在。

2。 php artisan make:provider 订阅服务提供者

<?php

namespace App\Providers;

use App\Observers\SubscriptionObserver;
use App\Subscription;
use Illuminate\Support\ServiceProvider;

class SubscriptionServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        Subscription::observe(SubscriptionObserver::class);
    }
}

boot() 方法中的通知行。

3。 将提供者包含到 config/app.php

的提供者列表中
<?php

return [

    // other elements

    /*
    |------------------------------
    | Autoloaded Service Providers
    |------------------------------
    |
    | The service providers listed here will be automatically loaded on the
    | request to your application. Feel free to add your own services to
    | this array to grant expanded functionality to your applications.
    |
    */

    'providers' => [

        // other providers

        App\Providers\SubscriptionServiceProvider::class,

    ],
];

所有这些都可以跳过并在 boot() 模型的方法中完成,但显示的方式对我来说更容易维护。

https://stackoverflow.com/questions/60839127/

相关文章:

azure-devops - 创建与 Azure 资源管理器的服务连接时出错 : azure pip

azure-devops - 如何将 Yarn 注册表用作 Azure DevOps 工件上游源?

node.js - 从 lambda 向 sns 主题发布消息

reactjs - react Hook UseEffect 与类名

reactjs - Ant Design v4 卡片样式boxShadow

python - 有没有办法从图形图像中提取数据并将其存储在 Excel 工作表或 csv 文件中?

javascript - 在 Redux Saga 中使用 map 功能进行 fork

typescript - 类型 'Readonly

reactjs - 在创建或处理 React 应用程序时,我是否需要始终连接到互联网?

date - 如何在 DART(Flutter)中舍入最接近 30 分钟间隔的日期时间?