当前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, ...]);
的代码一般写的所有车型(没有指定一个),所以你可以把它们放在一个trait
里面,并且像这样调用它:
$ model-> doSync('many_to_many_relation',$ listArray);
希望这有助于:)
同步功能应该设置新的列表。所以,如果你在公司表中有一个名称字段,那么你可以执行'$ user-> companies() - > pluck('name')'获得新的公司名单。 – Sandeesh