因为firstOrCreate()
在Laravel Eloquent中,我想知道是否有可以创建记录的功能或者是否存在,更新当前的记录?
或者我必须自己编写吗?
我无法在文档中找到任何内容,但这不是第一次,我在文档中找到了关于Eloquent的内容。
答案 0 :(得分:4)
你差点把它命名。 :)
$instance = Model::updateOrCreate(['id' => $id], $newAttributes);
如果$id
为null,则会创建并保存新实例,否则将更新。
答案 1 :(得分:2)
你需要在更新之前找到模型,对吧?您不能仅仅因为数据库中没有具有此类(新)属性的模型而调用Model::firstOrUpdate($newAttributes)
。
予。即您必须知道某个模型的唯一属性,例如id
。在此之后,您可以获取它并使用新属性调用update
方法:Model::firstOrNew(['id' => $id])->update($newAttributes)
。 $id
此处可以是null
,在这种情况下,新模型将被实例化(但不会保存)。
正如您所看到的,此代码很短,但当然,如果您愿意,可以将其放入方法中。
答案 2 :(得分:0)
更直接,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;
}