Laravel 4 - Inserting multiple records when using the hasMany relationship

谁说我不能喝 提交于 2019-12-03 15:14:59
TLGreg

save() expects a single model, saveMany() expects an array of models, and not assoicative array of the data.

But saveMany() will not insert with a single query, it will actually loop trough the models and insert one by one (note: L3 also did this).

If you need to insert a larger set of records don't use the ORM, use the query builder, how Manuel Pedrera wrote the first example code.

Just for the record here is how you would use saveMany():

$post = Post::find(1);

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

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

This may not be exactly what you are looking for, since it's not using Eloquent, but it should get your seeds done. You can use DB::insert(), like this:

$postId = 1;

DB::table('comments')->insert(array(
    array(
        'message' => 'A new comment.',
        'post_id' => $postId),
    array(
        'message' => 'A second comment', 
        'post_id' => $postId
    ),
));

As an alternative, you could do this using Eloquent too, but it should be done in the opposite way: setting the related model in the "childs". This is what the official docs say:

Associating Models (Belongs To)

When updating a belongsTo relationship, you may use the associate method. This method will set the foreign key on the child model

I think it's done this way because in the database, the "child" model is the one which contains the foreign key to the "parent" (in this case, post_id).

The code should look like this:

$post = Post::find(1);

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

foreach ($comments as $commentAttributes) {
    $comment = new Comment($commentAttributes);
    $comment->post()->associate($post);
    $comment->save();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!