更新 Laravel 5.4 中的对象数组
Update an array of objects in Laravel 5.4
我在 Angular 应用程序上使用 Laravel 作为 API。其中一个控制器必须更新一组对象。
这个数组,来自 Angular,可能有
- 相同的对象但具有不同的属性
- 其中一个对象可能已被删除
- 新对象
因此,我不能只更新我拥有的对象,因为我需要删除数组中不再存在的记录并创建新记录。
目前,我有一个不太好的解决方案,即删除所有以前的记录并根据数组创建新记录。像这样:
Sample::where('contest_id', $request->get('contest_id'))
->where('type', '0')
->delete();
$samples = $request->get('samples');
foreach ( $samples as $sample ) {
Sample::create($sample);
}
但是,我想添加一个 activity 记录器来跟踪更改,但上述解决方案没有帮助。 activity 记录器的工作方式如下:
activity()
->causedBy($user)
->performedOn($sample)
->withProperties($properties)
->log('update'); //or new or delete
其中$properties
是这样的:
$properties = [
'property' => [
'old' => $old_sample, // empty on creating new record
'new' => $sample // empty on deleting old record
],
];
有什么建议吗?
当您需要更新记录时,您不能让您的前端也发送 sample_id 吗?如果你能做到这一点,你可以玩 Collections 并制作这样的东西:
// Retrieves all samples and turn them into a Collection
$samples = collect($request->get('samples'));
// Gets only the sample_ids that are not null and greater than zero
$changed_ids = $samples->pluck('sample_id')->filter()->all();
// These samples are new - create them
$new_samples = $samples->whereStrict('sample_id', null);
// These samples were changed - update them
$changed_samples = $samples->whereIn('sample_id', $changed_ids);
// These samples were deleted - remove them
$deleted_samples = Sample::whereNotIn('sample_id', $changed_ids);
您的解决方案似乎是最有效的,您可以不检索要删除的记录,将它们记录为已删除然后实际删除它们,然后记录新记录的创建吗?
在那种情况下,您的日志实际上更好地反映了所发生的 activity。
我在 Angular 应用程序上使用 Laravel 作为 API。其中一个控制器必须更新一组对象。
这个数组,来自 Angular,可能有
- 相同的对象但具有不同的属性
- 其中一个对象可能已被删除
- 新对象
因此,我不能只更新我拥有的对象,因为我需要删除数组中不再存在的记录并创建新记录。
目前,我有一个不太好的解决方案,即删除所有以前的记录并根据数组创建新记录。像这样:
Sample::where('contest_id', $request->get('contest_id'))
->where('type', '0')
->delete();
$samples = $request->get('samples');
foreach ( $samples as $sample ) {
Sample::create($sample);
}
但是,我想添加一个 activity 记录器来跟踪更改,但上述解决方案没有帮助。 activity 记录器的工作方式如下:
activity()
->causedBy($user)
->performedOn($sample)
->withProperties($properties)
->log('update'); //or new or delete
其中$properties
是这样的:
$properties = [
'property' => [
'old' => $old_sample, // empty on creating new record
'new' => $sample // empty on deleting old record
],
];
有什么建议吗?
当您需要更新记录时,您不能让您的前端也发送 sample_id 吗?如果你能做到这一点,你可以玩 Collections 并制作这样的东西:
// Retrieves all samples and turn them into a Collection
$samples = collect($request->get('samples'));
// Gets only the sample_ids that are not null and greater than zero
$changed_ids = $samples->pluck('sample_id')->filter()->all();
// These samples are new - create them
$new_samples = $samples->whereStrict('sample_id', null);
// These samples were changed - update them
$changed_samples = $samples->whereIn('sample_id', $changed_ids);
// These samples were deleted - remove them
$deleted_samples = Sample::whereNotIn('sample_id', $changed_ids);
您的解决方案似乎是最有效的,您可以不检索要删除的记录,将它们记录为已删除然后实际删除它们,然后记录新记录的创建吗?
在那种情况下,您的日志实际上更好地反映了所发生的 activity。