Clone an Eloquent object including all relationships?

后端 未结 10 695
我寻月下人不归
我寻月下人不归 2020-12-01 01:24

Is there any way to easily clone an Eloquent object, including all of its relationships?

For example, if I had these tables:

users ( id, name, email          


        
10条回答
  •  孤城傲影
    2020-12-01 01:49

    Here's another way to do it if the other solutions don't appease you:

    with('segments.stops','billingItems','invoiceItems.applyTo')->findOrFail($id);
    
    $booking->id = null;
    $booking->exists = false;
    $booking->number = null;
    $booking->confirmed_date_utc = null;
    $booking->save();
    
    $now = CarbonDate::now($booking->company->timezone);
    
    foreach($booking->segments as $seg) {
        $seg->id = null;
        $seg->exists = false;
        $seg->booking_id = $booking->id;
        $seg->save();
    
        foreach($seg->stops as $stop) {
            $stop->id = null;
            $stop->exists = false;
            $stop->segment_id = $seg->id;
            $stop->save();
        }
    }
    
    foreach($booking->billingItems as $bi) {
        $bi->id = null;
        $bi->exists = false;
        $bi->booking_id = $booking->id;
        $bi->save();
    }
    
    $iiMap = [];
    
    foreach($booking->invoiceItems as $ii) {
        $oldId = $ii->id;
        $ii->id = null;
        $ii->exists = false;
        $ii->booking_id = $booking->id;
        $ii->save();
        $iiMap[$oldId] = $ii->id;
    }
    
    foreach($booking->invoiceItems as $ii) {
        $newIds = [];
        foreach($ii->applyTo as $at) {
            $newIds[] = $iiMap[$at->id];
        }
        $ii->applyTo()->sync($newIds);
    }
    

    The trick is to wipe the id and exists properties so that Laravel will create a new record.

    Cloning self-relationships is a little tricky but I've included an example. You just have to create a mapping of old ids to new ids and then re-sync.

提交回复
热议问题