Laravel 单字段更新的多态多对多

Laravel Polymoprhic Many to Many with one field updating

我有一个 Equipment 模型,它是多态多对多模型和其他一些模型。

这是我想不通的问题。当一个装备被添加到另一个模型时,每次装备上的hours都会改变。所有其他字段、sn、make、model 都是静态的。我想对此进行设置,以便记录对小时字段的每次更改 - 这样我就可以查询历史记录。

我应该把时间移到 equipables table 吗?添加一个枢轴table?设置它的最佳方法是什么?

以下是此模型和 Equipables 多边形关系迁移的概述。

        Schema::create('equipment', function (Blueprint $table) {
            $table->id();
            $table->string('sn')->index();
            $table->string('make');
            $table->string('model');
            $table->string('stock');
            $table->string('hours');
            $table->timestamps();
        });

        Schema::create('equipables', function (Blueprint $table) {
            $table->integer("equipment_id");
            $table->integer("equipable_id");
            $table->string("equipable_type");
            $table->timestamps();
        });

感谢您提供的任何帮助。

您可以通过创建事件来实现此方案,并在任何目标模型创建或更新时调用它。通过这种方式,您可以跟踪他们的行为并更新设备table。
比如模型A和设备有morph关系,我通过运行php artisan make:event ACreated创建了一个名为ACreated的事件,创建后调用这个事件A 模型的实例。

$a = A::create([
    // Some sample array data here
]);

event(new ACreated($a));

一个创建的事件:

class ACreated
{
    public $a;

    public function __construct(App\Models\A $a){
        $this->a = $a;
    }
}

然后在你的 EventServiceProvider, link ACreated 事件中给一个监听器,例如 AWasCreated听众(php artisan make:listener AWasCreated).

事件服务提供商:

protected $listen = [
    App\Event\ACreated::class => [
        App\Listener\AWasCreated::class,
    ],
];

最后,在侦听器中执行您的逻辑:

AWasCreated:

class AWasCreated
{
    public function handle($event){
        $a = $event->a;
        $a->equipment->increment('hours');
    }
}