mardi 9 mai 2017

Laravel belongsToMany add without saving

I would like to create en Eloquent model without saving it to the database right away. I would, however, like to include all relationships so that with a single "push()" call I could save the entire structure.

The below is an example of what I would like to do.

class Post extends Eloquent
{
    public function tags()
    {
        return $this->belongsToMany('Tag');
    }
}

class Tag extends Eloquent
{
    public function posts()
    {
        return $this->belongsToMany('Post');
    }
}

I understand I can simply do this now:

$post = new Post;
$post->save();
$post->tags()->save($tag);

However, what I really am looking for is:

$post = new Post;
$post->tags()->add($tag);
$post->push();

The best option I can think of right now is not to use pivots, and instead include all of my pivot tables as fully fledged Eloquent models too, but it seems a bit of an overkill (plus I can only assume somebody has already come up with a better way to do this!).

Many thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire