Laravel雄辩ORM保存:更新vs创建 [英] Laravel Eloquent ORM save: update vs create

查看:83
本文介绍了Laravel雄辩ORM保存:更新vs创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张表,我试图使用 save()方法来更新/创建行。问题是它总是创建新行。以下代码每次运行时都会提供大约12行。它们在插入之前没有唯一的 id ,而是 name DateTimeCode的组合是唯一的。有没有办法使用这两个,以便laravel将它们识别为 exists()?应该考虑使用(如果有)创建更新

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?

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();
};


推荐答案

我认为在这种情况下你需要搜索在更新或创建之前:

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();
};

这篇关于Laravel雄辩ORM保存:更新vs创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆