创建或更新 - Laravel 4.1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20752309/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:48:03  来源:igfitidea点击:

Create or Update - Laravel 4.1

phplaravellaravel-4

提问by Jazerix

As there is firstOrCreate()in Laravel Eloquent, I was wondering if there was a function that could either create a record or if it exists, update the current one?

正如firstOrCreate()Laravel Eloquent 中的那样,我想知道是否有一个函数可以创建记录,或者如果它存在,则更新当前记录?

Or would I have to write my own one?

还是我必须自己写一个?

I wasn't able to find anything in the documentation, but it's not the first time, I've found stuff about Eloquent elsewhere than the docs.

我无法在文档中找到任何内容,但这不是第一次,我在文档以外的其他地方找到了有关 Eloquent 的内容。

采纳答案by neoascetic

You need to find model before updating it, right? You cannot just call Model::firstOrUpdate($newAttributes)simply because there is no model in database with such (new) attributes.

您需要在更新之前找到模型,对吗?您不能仅仅Model::firstOrUpdate($newAttributes)因为数据库中没有具有此类(新)属性的模型而调用。

I. e. you must know some model's unique attribute, for example, an id. After this, you can fetch it and call updatemethod with new attributes: Model::firstOrNew(['id' => $id])->update($newAttributes). $idhere can be null, in this case new model will be instantiated (but not saved).

IE。您必须知道某个模型的唯一属性,例如,一个id. 在此之后,你可以把它拿来和调用update方法与新的属性:Model::firstOrNew(['id' => $id])->update($newAttributes)$id这里可以null,在这种情况下,新模型将被实例化(但不保存)。

As you can see, this code is pretty short, but of course, you might put it into method if you wish.

如您所见,这段代码很短,当然,如果您愿意,也可以将其放入方法中。

回答by Jocelyn

You nearly named it. :)

你差点给它起名字。:)

$instance = Model::updateOrCreate(['id' => $id], $newAttributes);

If $idis null then a new instance will be created and saved, else it will be updated.

如果$id为 null,则将创建并保存一个新实例,否则将对其进行更新。

回答by Ronald Hulshof

More straight forward and DRY would it be to add the following method to your BaseModel:

更直接和 DRY 将以下方法添加到您的 BaseModel:

public function write($input, $key = 'id')
{
    // Instantiate new OR existing object
    if (! empty($input[$key]))
        $resource = $this->findOrFail($input[$key]);
    else
        $resource = $this; // Use a clone to prevent overwriting the same object in case of recursion

    // Fill object with user input using Mass Assignment
    $resource->fill($input);

    // Save data to db
    if (! $resource->save())
        App::abort(500, 'Could not save resource');

    return $resource;
}