vendredi 27 juillet 2018

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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire