2013-12-23 75 views
2

由於在Laravel Eloquent中有firstOrCreate() ,我想知道是否有可以創建記錄的函數或者是否存在,更新當前的記錄?創建或更新 - Laravel 4.1

或者我需要自己寫一個嗎?

我在文檔中找不到任何東西,但這不是第一次,我發現了有關其他地方的文章,而不是文檔。

回答

2

您需要在更新之前找到模型,對吧?你不能僅僅因爲在這個(新的)屬性的數據庫中沒有模型而僅僅調用Model::firstOrUpdate($newAttributes)

I.e。您必須知道某個模型的獨特屬性,例如id。在此之後,您可以獲取它並使用新屬性調用update方法:Model::firstOrNew(['id' => $id])->update($newAttributes)$id這裏可以是null,在這種情況下,新模型將被實例化(但不保存)。你可以看到,這段代碼非常短,但是當然,如​​果你願意的話,你可以把它放到方法中去。

+0

ahh,我明白了,謝謝 – Jazerix

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; 
} 
+0

這是不好做的模型類中的http相關 – neoascetic

+0

然後把它放在你的BaseController上... –

4

你幾乎把它命名。 :)

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

如果$id爲null,則一個新的實例將被創建並保存,否則將被更新。