Programing

모든 관계를 포함하여 Eloquent 객체를 복제 하시겠습니까?

lottogame 2020. 12. 7. 07:41
반응형

모든 관계를 포함하여 Eloquent 객체를 복제 하시겠습니까?


모든 관계를 포함하여 Eloquent 객체를 쉽게 복제 할 수있는 방법이 있습니까?

예를 들어 다음 테이블이있는 경우 :

users ( id, name, email )
roles ( id, name )
user_roles ( user_id, role_id )

에서 새로운 행을 생성 이외에 users모든 열을 제외하고는 동일한 인으로 표 id, 또한에서 새로운 행을 생성한다 user_roles새로운 사용자에게 동일한 역할을 할당 테이블.

이 같은:

$user = User::find(1);
$new_user = $user->clone();

사용자 모델이있는 곳

class User extends Eloquent {
    public function roles() {
        return $this->hasMany('Role', 'user_roles');
    }
}

belongsToMany 관계에 대해 laravel 4.2에서 테스트되었습니다.

모델에있는 경우 :

    //copy attributes
    $new = $this->replicate();

    //save model before you recreate relations (so it has an id)
    $new->push();

    //reset relations on EXISTING MODEL (this way you can control which ones will be loaded
    $this->relations = [];

    //load relations on EXISTING MODEL
    $this->load('relation1','relation2');

    //re-sync everything
    foreach ($this->relations as $relationName => $values){
        $new->{$relationName}()->sync($values);
    }

eloquent가 제공하는 복제 기능을 사용해 볼 수도 있습니다.

http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_replicate

$user = User::find(1);
$new_user = $user->replicate();
$new_user->push();

시도해 볼 수 있습니다 ( Object Cloning ) :

$user = User::find(1);
$new_user = clone $user;

clone딥 복사가 아니기 때문에 사용 가능한 자식 개체가 있으면 자식 개체가 복사되지 않으며이 경우 clone수동으로 자식 개체를 복사해야합니다 . 예를 들면 :

$user = User::with('role')->find(1);
$new_user = clone $user; // copy the $user
$new_user->role = clone $user->role; // copy the $user->role

귀하의 경우 roles에는 Role객체 모음이 될 것이므로 모음의 각 항목 Role object은를 사용하여 수동으로 복사해야 clone합니다.

또한 rolesusing with로드하지 않으면로드 되지 않거나에서 사용할 수 없으며 $user호출 할 때 $user->roles해당 객체가 해당 호출 후 런타임에로드된다는 점을 알고 있어야합니다. 이 $user->roles때까지 roles로드되지 않습니다.

최신 정보:

이 대답은 Larave-4이제 Laravel이 다음과 같은 replicate()방법을 제공합니다 .

$user = User::find(1);
$newUser = $user->replicate();
// ...

Laravel 5. hasMany 관계로 테스트되었습니다.

$model = User::find($id);

$model->load('invoices');

$newModel = $model->replicate();
$newModel->push();


foreach($model->getRelations() as $relation => $items){
    foreach($items as $item){
        unset($item->id);
        $newModel->{$relation}()->create($item->toArray());
    }
}

다음은 게시 한대로 belongsToMany 대신 모든 hasMany 관계를 복제하는 @ sabrina-gelbart의 업데이트 된 솔루션 버전입니다.

    //copy attributes from original model
    $newRecord = $original->replicate();
    // Reset any fields needed to connect to another parent, etc
    $newRecord->some_id = $otherParent->id;
    //save model before you recreate relations (so it has an id)
    $newRecord->push();
    //reset relations on EXISTING MODEL (this way you can control which ones will be loaded
    $original->relations = [];
    //load relations on EXISTING MODEL
    $original->load('somerelationship', 'anotherrelationship');
    //re-sync the child relationships
    $relations = $original->getRelations();
    foreach ($relations as $relation) {
        foreach ($relation as $relationRecord) {
            $newRelationship = $relationRecord->replicate();
            $newRelationship->some_parent_id = $newRecord->id;
            $newRelationship->push();
        }
    }

다음 코드를 사용하여 $ user라는 컬렉션이있는 경우 모든 관계를 포함하여 이전 컬렉션과 동일한 새 컬렉션을 만듭니다.

$new_user = new \Illuminate\Database\Eloquent\Collection ( $user->all() );

이 코드는 laravel 5 용입니다.


이것은 laravel 5.8에 있으며 이전 버전에서는 시도하지 않았습니다.

//# this will clone $eloquent and asign all $eloquent->$withoutProperties = null
$cloned = $eloquent->cloneWithout(Array $withoutProperties)

편집, 바로 오늘 2019 년 4 월 7 일 laravel 5.8.10 출시

지금 복제를 사용할 수 있습니다

$post = Post::find(1);
$newPost = $post->replicate();
$newPost->save();

원하는 관계로 객체를 가져오고 그 후에 복제하면 검색 한 모든 관계도 복제됩니다. 예를 들면 :

$oldUser = User::with('roles')->find(1);
$newUser = $oldUser->replicate();

다른 솔루션이 당신을 달래주지 않는 경우 다른 방법이 있습니다.

<?php
/** @var \App\Models\Booking $booking */
$booking = Booking::query()->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);
}

트릭은 Laravel이 새 레코드를 만들도록 idexists속성을 지우는 것입니다.

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.

참고URL : https://stackoverflow.com/questions/23895126/clone-an-eloquent-object-including-all-relationships

반응형