【问题标题】:automatically assign value to a field in a laravel model自动为 laravel 模型中的字段赋值
【发布时间】:2020-03-25 06:31:18
【问题描述】:

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

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

但这对我不起作用,因为我认为 mutator 就像它的名字一样,它改变了我为这个字段发送的值,在我的情况下,我需要在每次创建新记录时自动添加一个,那我该怎么做呢?

【问题讨论】:

标签: php laravel eloquent


【解决方案1】:

正如@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 SubscriptionServiceProvider

<?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()模型的方法中跳过和完成,但显示的方式对我来说更容易维护。

【讨论】:

  • 很好的答案,我在文档中阅读了这个,虽然我不明白一些东西,但我已经有了更清楚的东西。当您说我可以在启动时注册该提供程序时,还有一个疑问,您是指 AppServiceProvider 中的方法吗?
  • 如果你在 AppServiceProvider 中监听模型的观察者,你可以跳过第 2 步和第 3 步。你可以在 AppServiceProvider 中进行,但我喜欢这样分开。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 2015-11-13
  • 1970-01-01
相关资源
最近更新 更多