目前revisionable
不支持多对多关系。但我用以下代码解决了这个问题:
/**
* Make revision and sync for many to many relations
*
* @param string $relation
* @param array $list
* @return array
*/
public function doSync($relation, $list)
{
$rel = $this->{$relation}();
$old = $rel->pluck('id')->implode(',');
$rel->sync($list);
$new = $rel->pluck('id')->implode(',');
storePivotRevision($this, $relation, $old, $new);
}
/**
* Store revision for pivot tables
*
* @param string $relation
* @param string $old
* @param string $new
* @return null
*/
function storePivotRevision($relation, $old, $new)
{
if ($old == $new) {
return;
}
DB::table('revisions')->insert([
'revisionable_type' => get_class($this),
'revisionable_id' => $model->id,
'user_id' => auth()->check() ? auth()->user()->id : null,
'key' => "{$relation}_pivot",
'old_value' => $old,
'new_value' => $new,
'created_at' => now(),
'updated_at' => now(),
]);
}
现在代替
$user->roles()->sync([1, 2, 3, ...]);
你可以使用
$user->doSync('roles', [1, 2, 3, ...]);
该代码通常是为所有模型编写的(未指定为一个),因此您可以将它们放在 a 中trait
并像这样调用它:
$model->doSync('many_to_many_relation', $listArray);
希望这可以帮助 :)