panthro
panthro

Reputation: 24061

Inserting a new relationship

I'm just looking through the docs:

$post = Post::find(1);

$comments = array(
    new Comment(array('message' => 'A new comment.')),
    new Comment(array('message' => 'A second comment.')),
);

$post->comments()->save($comments);

I've implemented something similar to the above on my site, my question is, I wish to also insert a new Post at the same time, is there a way to do this, instead of using find?

Also what happens if the insert of the post fails, can I prevent the comments from being inserted?

Upvotes: 0

Views: 51

Answers (3)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81167

Parent of the relationship must be saved prior to saving related models. Can't be done in 1 go. (btw push won't work for it either, in case you wonder).

$post = Post::create([ ... post data here ...]);
// or
$post = new Post;
$post->whatever = 'someValue';
$post->save();

// then
$post->comments()->saveMany($comments);

Upvotes: 1

Sher Afgan
Sher Afgan

Reputation: 1234

Why not first create a post then attach the related model something like this.

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

Then iterate through comments and assign the post_id attribute in comment table.

The id field of post model will be available if the post exists.

$comment = new Comment();
$comment->post_id = $post->id;
$comment->save();

Upvotes: 0

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

You can probably do it this way:

$post = new Post();

$post->title = 'my title';

$post->save();

$comments = array(
    new Comment(array('message' => 'A new comment.')),
    new Comment(array('message' => 'A second comment.')),
);

$post->comments()->saveMany($comments);

this way you will create new post and save comments for it. I haven't tested what happens if something goes wrong but I assume comments won't be inserted because there won't be related post id.

Upvotes: 0

Related Questions