复制Laravel系列-Laravel 5.3
我正在复制trips表。在trips表单上,有一个下拉列表来选择物种。一个用户可以选择许多物种来进行分类。我很难复制这个物种表,因为它在自己的表中,而且是一个集合。所以使用“复制”是行不通的 这就是我现在复制trips表的方式:复制Laravel系列-Laravel 5.3,laravel,collections,replication,laravel-5.3,Laravel,Collections,Replication,Laravel 5.3,我正在复制trips表。在trips表单上,有一个下拉列表来选择物种。一个用户可以选择许多物种来进行分类。我很难复制这个物种表,因为它在自己的表中,而且是一个集合。所以使用“复制”是行不通的 这就是我现在复制trips表的方式: public function replicateTrip (Request $request, $slug, $id) { $listing = $request->user()->listings()->where('slug',
public function replicateTrip (Request $request, $slug, $id) {
$listing = $request->user()->listings()->where('slug', $slug)->first();
$trip = $listing->trips()->where('id', $id)->first();
$replicateTrip = Trip::find($trip->id);
// This is how im getting the species from the species table
$replicateSpecies = DB::table('species_trip')->where('trip_id', $id)->get();
$newTask = $replicateTrip->replicate();
$newTask->save();
return redirect()->back();
}
如果我在克隆当前旅行时添加$replicateSpecies变量,我会得到:
我需要将我最初旅行中的物种数组复制到物种表中,我不能只使用“复制”,因为它是一个集合
所以我的问题是如何复制这个集合?或者,如果有其他方法可以这样做?您可以尝试以下方法:
public function replicateTrip (Request $request, $slug, $id) {
$listing = $request->user()->listings()->where('slug', $slug)->first();
$trip = $listing->trips()->where('id', $id)->first();
$replicateTrip = Trip::find($trip->id);
// This is how im getting the species from the species table
$replicateSpecies = DB::table('species_trip')->where('trip_id', $id)->get();
$newTask = $replicateTrip->replicate();
$newTask->save();
$replicateSpecies->each(function ($item, $key) use($newTask) {
$copy = $item->replicate();
$copy->trip_id = $newTask->id;
$copy->save();
})
return redirect()->back();
}