0

我目前正在为 Laravel v5.4.23 使用 Revisionable Package v1.28.0,这在大多数情况下是一对很好的组合。

但是现在我在修改输入数组时遇到了一点问题。输入元素<input name="company_list[]">不是什么大问题,但对于可修改的包来说它是不可见的。因此不会将任何更改写入数据库。Add()的请求显示了输入字段的内容。

"company_list" => array:3 [0 => "12", 1 => "10",2 => "2"]

输入数组将与用户模型同步。

$user->companies()->sync($request->input('company_list',[]))

有没有办法获取更改并将 ID 转换为特定名称?

非常感谢!

4

1 回答 1

0

目前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);

希望这可以帮助 :)

于 2017-11-11T22:10:30.760 回答