Laravel 4 - 使用 hasMany 关系时插入多条记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20248107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:40:31  来源:igfitidea点击:

Laravel 4 - Inserting multiple records when using the hasMany relationship

laravellaravel-4

提问by LiquidB

Still finding my feet with Laravel 4 and I'm a little unsure as to why this isn't working.

仍然在 Laravel 4 上找到我的脚,我有点不确定为什么这不起作用。

In L3 I was able to insert multiple records to a table like so...

在 L3 中,我能够像这样将多条记录插入到一​​个表中......

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

$post = Post::find(1);

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

However when I try to do similar now either the records are inserted without the foreign key, like so...

但是,当我现在尝试做类似的事情时,要么在没有外键的情况下插入记录,就像这样......

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

$post = Post::first();

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

Or (and after some Googling) I try the following and get a preg_match() expects parameter 2 to be string, array given

或者(经过一些谷歌搜索)我尝试以下并得到一个 preg_match() expects parameter 2 to be string, array given

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

$post = Post::first();

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

As well as ...->save($comments)I've tried ...->saveMany()and ...->associate()but I have the same issue as the last example.

以及...->save($comments)我已经尝试过...->saveMany()...->associate()但我遇到了与上一个示例相同的问题。

On a side note, I do realise that I've wrapped the multidimensional array in an object but that appears to be the correct way to do this. I have tried not doing but that also fails.

附带说明一下,我确实意识到我已将多维数组包装在一个对象中,但这似乎是执行此操作的正确方法。我试过不做,但也失败了。

I should probably point out that I'm running a seed command through artisan.

我可能应该指出我正在通过 artisan 运行一个种子命令。

Edit:This is the full preg_matcherror from the log file

编辑:这是preg_match日志文件中的完整错误

[2013-11-27 16:43:39] log.ERROR: exception 'ErrorException' with message 'preg_match() expects parameter 2 to be string, array given' in /Applications/MAMP/htdocs/project/www/bootstrap/compiled.php:6315

[2013-11-27 16:43:39] log.ERROR: exception 'ErrorException' with message 'preg_match() expects parameter 2 to be string, array given' in /Applications/MAMP/htdocs/project/www/bootstrap/compiled.php:6315

回答by Manuel Pedrera

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:

这可能不是您正在寻找的,因为它没有使用 Eloquent,但它应该可以完成您的种子。你可以使用DB::insert(),像这样:

$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:

作为替代方案,您也可以使用 Eloquent 执行此操作,但应该以相反的方式完成:在“childs”中设置相关模型。这是官方文档所说的:

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

关联模型(属于)

当更新一个belongsTo 关系时,你可以使用associate 方法。此方法将在子模型上设置外键

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).

我认为这样做是因为在数据库中,“子”模型是包含“父”(在本例中为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();
}

回答by TLGreg

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

save()期望单个模型,saveMany()期望模型数组,而不是数据的关联数组。

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).

saveMany()不会插入单个查询,它实际上会遍历模型并一个一个插入(注意:L3 也这样做了)。

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

如果您需要插入更大的记录集,请不要使用 ORM,请使用查询构建器,Manuel Pedrera是如何编写第一个示例代码的。

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

仅作记录,您将如何使用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);