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

Liq*_*idB 5 laravel laravel-4

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

在L3中我能够将多个记录插入到表中,如此...

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

$post = Post::find(1);

$post->comments()->save($comments);
Run Code Online (Sandbox Code Playgroud)

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

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

$post = Post::first();

$post->comments()->insert($comments);
Run Code Online (Sandbox Code Playgroud)

或者(以及一些谷歌搜索后)我尝试以下内容并得到一个 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);
Run Code Online (Sandbox Code Playgroud)

除了...->save($comments)我试过...->saveMany()...->associate(),但我有同样的问题,因为最后一个例子.

在旁注中,我确实意识到我已经将多维数组包装在一个对象中,但这似乎是执行此操作的正确方法.我试过没做但但也失败了.

我应该指出,我正在通过工匠运行种子命令.

编辑: 这是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

Man*_*era 17

这可能不是你想要的,因为它不是使用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
    ),
));
Run Code Online (Sandbox Code Playgroud)

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

关联模型(属于)

更新belongsTo关系时,您可以使用associate方法.此方法将在子模型上设置外键

我认为这样做是因为在数据库中,"子"模型是包含"父"的外键的模型(在本例中post_id).

代码应该如下所示:

$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();
}
Run Code Online (Sandbox Code Playgroud)


小智 15

save()期望一个模型,saveMany()期望一组模型,而不是数据的分析数组.

但是saveMany()不会插入单个查询,它实际上将循环通过模型并逐个插入(注意:L3也这样做).

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

只是为了记录这里你将如何使用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);
Run Code Online (Sandbox Code Playgroud)