小编Liq*_*idB的帖子

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

仍然用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(),但我有同样的问题,因为最后一个例子.

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

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

编辑: 这是 …

laravel laravel-4

5
推荐指数
2
解决办法
2万
查看次数

标签 统计

laravel ×1

laravel-4 ×1