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

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

问题描述

我有一个表,我正在尝试使用 save() 方法来更新/创建行.问题是它总是创建新行.以下代码每次运行时都会给我大约 12 行代码.在插入它们之前,它们没有唯一的 id,但 nameDateTimeCode 的组合是唯一的.有没有办法使用这两个来让 laravel 将它们识别为 exist()?我应该考虑将 if existscreateupdate 一起使用吗?

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 Eloquent ORM 保存:更新与创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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