代码之家  ›  专栏  ›  技术社区  ›  Patrick L.

一对多伙伴

  •  1
  • Patrick L.  · 技术社区  · 7 年前

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

    评论 模型:

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

    这个 商店 模型是:

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

    所以这种关系是一对多的

    我想复制 商店 把它们附在另一个上面 商店 :

    $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 回复  |  直到 7 年前
        1
  •  2
  •   d3jn    7 年前

    你可以利用 createMany 关系方式:

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

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

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

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

        2
  •  0
  •   Namoshek    7 年前

    要复制注释,首先需要复制它们。然后您可以将它们与所属模型关联起来:

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