我不会将更新存储在名为audits_pivot
的单独表中的数据透视表中。
为此,我需要对模型(状态)上的attached
事件进行某种类型的钩子,据我发现doesn't really存在。我可以做的是在自定义数据透视表类(LicenceState)上侦听要调用的static::saving
,因为这等效于“ attached”。不幸的是static::saving
的回调函数不包含有关数据透视表所附加内容的任何信息。
[有来自fico7489的this one之类的库,但与我正在使用的Laravel Nova不兼容。
我如何访问数据透视行附加到的模型的名称和ID之类的内容?
<?php
namespace App;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Database\Eloquent\Relations\Pivot as EloquentPivot;
use OwenIt\Auditing\Auditable as AuditableTrait;
use OwenIt\Auditing\Contracts\Auditable;
abstract class Pivot extends EloquentPivot implements Auditable
{
use AuditableTrait;
public static function boot()
{
parent::boot();
static::saving(function ($model) {
// How can I access here things like the name and Id of the Model that the pivot row was attached to?
// What I'm looking for is basically this:
// savePivotAudit('attached', 12, 'App\Licence', 'App\State', 51, '2020-01-14 13:55:58');
});
}
private function savePivotAudit($eventName, $id, $relation, $pivotId, $date)
{
return app('db')->table('audits_pivot')->insert([
'event' => $eventName,
'auditable_id' => $id,
'auditable_type' => $this->getMorphClass(),
'relation_id' => $pivotId,
'relation_type' => $relation,
'parent_updated_at' => $date,
]);
}
}
class License extends EloquentModel {}
class State extends EloquentModel
{
use AuditableTrait;
public function licenses()
{
return $this->belongsToMany(License::class)
->using(LicenseState::class);
}
}
class LicenseState extends Pivot {}
Accountant包可以满足您的需求。
[通过使用Eventually支持多对多关系(即数据透视表),该事件为attach()
,detach()
,updateExistingPivot()
,sync()
和toggle()
添加了事件。
甚至都不需要使用custom intermediate models。
文档涵盖了安装,配置和使用的所有方面。