一对多的同事

时间:2018-07-27 13:14:05

标签: laravel laravel-5 eloquent

我有一个模型Shop和一个模型Comment

Comment模型上:

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

Shop模型是:

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

所以这种关系是一对多的

我想复制Shop的所有注释并将它们附加到另一个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

有人知道如何处理一对多情况吗?

2 个答案:

答案 0 :(得分:2)

您可以使用createMany的关系方法:

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

如果一家商店可以有很多评论(也可以将其拆分为更多查询以提高存储效率),您还可以利用分块:

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

编辑:根据评论更改了我的答案。

答案 1 :(得分:0)

要复制评论,您首先需要复制它们。然后,您可以将它们与他们自己的模型相关联:

$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();
}