Laravel Eloquent ORM 保存:更新与创建
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19684925/
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
Laravel Eloquent ORM save: update vs create
提问by Wistar
I've got a table and I'm trying to use the save()
method to update/create lines. The problem is that it always create new lines. The following code gives me about 12 lines each time I run it. They don't have a unique id
before inserting them but the combination of name
and DateTimeCode
is unique. Is there's a way to use those two in order for laravel to recognize them as exist()
? Should I consider using if exist
with create
and update
instead?
我有一张表,我正在尝试使用该save()
方法来更新/创建行。问题是它总是创建新行。下面的代码每次运行时给我大约 12 行。他们没有一个独特的id
插在他们面前,但组合name
和DateTimeCode
独特。有没有办法使用这两个来让 Laravel 将它们识别为exist()
?我应该考虑使用if exist
与create
和update
呢?
foreach ($x as $y) {
$model = new Model;
$model->name = ''.$name[$x];
$model->DateTimeCode = ''.$DateTimeCode[$x];
$model->value = ''.$value[$x];
$model->someothervalue = ''.$someothervalue[$x];
$model->save();
};
回答by Hill
I assume this would work in laravel 4.x:
我认为这适用于 laravel 4.x:
foreach ($x as $y) {
$model = Model::firstOrCreate(array('name' => name[$x], 'DateTimeCode' => DateTimeCode[$x]));
$model->value = ''.$value[$x];
$model->someothervalue = ''.$someothervalue[$x];
$model->save();
};
回答by Antonio Carlos Ribeiro
I think that in this case you will need to search for it before updating or creating:
我认为在这种情况下,您需要在更新或创建之前搜索它:
foreach ($x as $y) {
$model = Model::where('name', name[$x])->where('DateTimeCode', DateTimeCode[$x])->first();
if( ! $model)
{
$model = new Model;
$model->name = ''.name[$x];
$model->DateTimeCode = ''.DateTimeCode[$x];
}
$model->value = ''.$value[$x];
$model->someothervalue = ''.$someothervalue[$x];
$model->save();
};