Patrick L.
Patrick L.

Reputation: 526

One To Many associate

I have a model Shop and a model Comment.

on the Comment model:

public function shop()
    {
        return $this->belongsTo('App\Shop', 'commentable_id');
    }

The Shop model is:

public function comments() {       
        return $this->hasMany('App\Comment', 'commentable_id');
    }

So the relationship is One To Many

I want to copy all the comments of a Shop and attach them to another Shop:

$shop = Shop::find(1);
$comments = $shop->comments()->pluck('id')->toArray(); // it works, i have all the ids of the comments

$othershop = Shop::find(2);
$othershop->comments()->associate($comments); // doesn't work
$othershop->comments()->attach($comments); // doesn't work

Anyone knows how to proceed with a One to Many situation?

Upvotes: 1

Views: 1589

Answers (2)

d3jn
d3jn

Reputation: 1410

You can utilize createMany method of relationship:

$othershop->comments()->createMany($shop->comments->toArray());

You can also utilize chunking if one shop can have many comments (split it into more queries to make it more memory efficient):

$shop->comments()->chunk(500, function ($comments) use ($othershop) {
    $othershop->comments()->createMany($comments->toArray());
});   

edit: changed my answer based on comments.

Upvotes: 2

Namoshek
Namoshek

Reputation: 6544

To copy comments, you first need to replicate them. Then you can associate them with their owning model:

$shop = Shop::find(1);
$otherShop = Shop::find(2);

$comments = $shop->comments()->get();
foreach ($comments as $comment) {
    $tmp = $comment->replicate();
    $tmp->shop()->associate($otherShop);
    $tmp->save();
}

Upvotes: 0

Related Questions