I'm trying to clone an entity and the OneTomany relation too. For some reason, the $entity->hasManyRelation() is not a function. :/
Here's my code.:
$clonedWorksheet = Worksheet::where('id', $id)->get()->load('records');
$worksheet = new Worksheet;
$worksheet->employee_id = $request->employee;
$worksheet->workday = $request->workday;
$worksheet->save();
foreach ($clonedWorksheet->records() as $clonedRecord) {
$record = new Record;
$record->from = $clonedRecord->from;
$record->to = $clonedRecord->to;
$record->estimated = $clonedRecord->estimated;
$record->place_id = $clonedRecord->place_id;
$record->worksheet_id = $worksheet->id;
$record->vehicle_id = $clonedRecord->vehicle_id;
$record->tool_id = $clonedRecord->tool_id;
$record->job_id = $clonedRecord->job_id;
$record->comment = $clonedRecord->comment;
$worksheet->records()->save($record);
}
Any other idea, or what am I doing wrong?
The problem is here.
foreach ($clonedWorksheet->records() as $clonedRecord) {
The records() is the method in the model that does the database query. The return is an eloquent relationship object. You want:
foreach($clonedWorksheet->records as $clonedRecord) {
Or
foreach ($clonedWorksheet->records()->get() as $clonedRecord) {
Models have a replicate function , which would cut the body of your loop down quite a bit to just:
$record = $cloneRecord->replicate();
$record->worksheet_id = $worksheet->id;
$record->save();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.