Reputation: 37
How to replicate/clone all data in a table that has self-relation in Laravel?
I have this table:
members table
id | member_id | company_id | name |
---|---|---|---|
1 | null | 23 | John |
2 | 1 | 23 | James |
3 | 1 | 23 | Ken |
4 | null | 23 | Test |
5 | 3 | 23 | Max |
EXISTING CODE
And I want to replicate all data that has company_id
of 23
using
$members = Members::where['company_id' => 23]->get();
foreach ($members as $member) {
$duplicate = $member->replicate()->fill(['company_id' => 24);
$duplicate->save();
}
Results of the code
members table
id | member_id | company_id | name |
---|---|---|---|
1 | null | 23 | John |
2 | 1 | 23 | James |
3 | 1 | 23 | Ken |
4 | null | 23 | Test |
5 | 3 | 23 | Max |
6 | null | 24 | John |
7 | 1 | 24 | James |
8 | 1 | 24 | Ken |
9 | null | 24 | Test |
10 | 3 | 24 | Max |
But in that code, the replication of self-relation is wrong. How can I do it?
Expected result
members table
id | member_id | company_id | name |
---|---|---|---|
1 | null | 23 | John |
2 | 1 | 23 | James |
3 | 1 | 23 | Ken |
4 | null | 23 | Test |
5 | 3 | 23 | Max |
6 | null | 24 | John |
7 | 6 | 24 | James |
8 | 6 | 24 | Ken |
9 | null | 24 | Test |
10 | 8 | 24 | Max |
I'm sorry if my English is messed up, but I hope you get the idea of what I'm trying to do. Thank you!
Upvotes: 0
Views: 108
Reputation: 15319
Try this .You have two options to replicate
$members = Members::where(['company_id' => 23])->get();
foreach ($members as $member) {
$duplicate = $member->replicate();
$duplicate->company_id=24;
$duplicate->save();
}
});
or
$members = Members::where(['company_id' => 23])->get();
foreach ($members as $member) {
$duplicate = $member->replicate()->fill(['company_id'=>24]);
$duplicate->save();
}
});
Updated
$members = Members::where(['company_id' => 23])->get();
$tempIdMap=[];
foreach ($members as $key=>$member) {
if($key==0){
$tempIdMap[$member->id]=$member->member_id;
}
$duplicate = $member->replicate()->fill(['company_id'=>24,'member_id'=>isset( $tempIdMap[$member->member_id])? $tempIdMap[$member->member_id]:null]);
$duplicate->save();
$tempIdMap[$member->id]=$duplicate->id;
}
Upvotes: 1