2016-08-09 18 views

回答

12

Model::create是圍繞$model = new MyModel(); $model->save() 的簡單包裝,請參見實現

/** 
* Save a new model and return the instance. 
* 
* @param array $attributes 
* @return static 
*/ 
public static function create(array $attributes = []) 
{ 
    $model = new static($attributes); 

    $model->save(); 

    return $model; 
} 

保存()

  • save()方法既用於節能新模式,並更新 現有的。在這裏您正在創建新模型或找到現有模型, 逐個設置其屬性,最後保存在數據庫中。

  • 節省()接受全鋒模型實例

    $comment = new App\Comment(['message' => 'A new comment.']); 
    
    $post = App\Post::find(1);` 
    
    $post->comments()->save($comment); 
    


創建()

  • 而在創建方法要傳遞數組,在設定的屬性 模型,並堅持在數據庫中一槍。
  • 創建()接受純 PHP數組

    $post = App\Post::find(1); 
    
    $comment = $post->comments()->create([ 
        'message' => 'A new comment.', 
    ]); 
    

    EDIT
    作爲@PawelMysior指出的那樣,使用create方法之前,一定要 標記,其值是安全的一組列通過批量賦值(例如name,birth_date等),我們需要通過提供一個名爲$ fillable的新屬性來更新我們的Eloquent模型。這簡直是​​包含安全通過質量分配,設置屬性的名稱數組: 例如: -

    類國家擴展模式{

    protected $fillable = [ 
        'name', 
        'area', 
        'language', 
        ]; 
    

    }

+0

感謝您回覆,但你能否給我更詳細的闡述。我閱讀了Laravel文檔,但從那裏我沒有多少想法。 –

+0

感謝您的詳細描述。 –

+4

需要注意的一點是:如果您打算使用create(),那麼您傳遞給它的所有屬性都必須列在模型的$ fillable屬性中。見:https://laravel.com/docs/master/eloquent#mass-assignment – PawelMysior

相關問題