Laravel 4-使用hasMany关系时插入多个记录 [英] Laravel 4 - Inserting multiple records when using the hasMany relationship
问题描述
仍然可以通过Laravel 4找到自己的脚,但是我不确定为什么它不起作用.
Still finding my feet with Laravel 4 and I'm a little unsure as to why this isn't working.
在L3中,我能够像这样将多个记录插入到表中...
In L3 I was able to insert multiple records to a table like so...
$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);
或者(在使用Google谷歌搜索之后),我尝试以下方法并得到一个preg_match() expects parameter 2 to be string, array given
Or (and after some Googling) I try the following and get a 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);
和...->save($comments)
一样,我也尝试过...->saveMany()
和...->associate()
,但是我遇到的问题与上一个示例相同.
As well as ...->save($comments)
I've tried ...->saveMany()
and ...->associate()
but I have the same issue as the last example.
在旁注中,我确实意识到我已经将多维数组包装在一个对象中,但这似乎是执行此操作的正确方法.我试过不做,但是也失败了.
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.
修改:
这是日志文件中的完整preg_match
错误
This is the full preg_match
error from the log file
[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
推荐答案
save()
需要单个模型,saveMany()
需要模型数组,而不是数据的关联数组.
save()
expects a single model, saveMany()
expects an array of models, and not assoicative array of the data.
但是saveMany()
不会通过单个查询插入,它实际上将遍历模型并逐个插入(注意:L3也这样做).
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).
如果您需要插入更大的记录集而不使用ORM,请使用查询生成器,如何
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.
这里只是记录一下您如何使用saveMany()
:
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);
这篇关于Laravel 4-使用hasMany关系时插入多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!