2015-08-27 38 views
2

我正在開發一個包含博客在內的多個內容的網站,並且我對質量保證有一些疑問。(Laravel)關於質量保障的質疑

當我在博客文章上發表評論時,我認爲'可填寫'字段是評論的主體,文章ID和parent_comment_id(可選,僅用於對評論的回覆),但是當我走到

ArticleComment::create([ 
      'author_id' => Auth::user()->id, 
      'body' => $request->input('body'), 
      'article_id' => $request->input('article_id'), 
      'parent_comment_id' => $request->input('parent_comment_id') 
     ]); 

我發現,即使是AUTHOR_ID場應該是質量,分配,以便有它持久化到數據庫(而不是得到一個外鍵故障)。 我發現將裝配從一個新的實例的註釋,保存它唯一的選擇:

$comment = new App\ArticleComment(); 
$comment->author_id = Auth::user()->id; 
$comment->body = $request->input('body'); 
$comment->article_id = $request->input('article_id'); 
$comment->parent_comment_id = $request->input('parent_comment_id'); 
$comment->save() 

但在這種情況下,就沒有必要有任何「可填寫」字段,因爲這種方式不會產生任何批量分配例外。

我知道質量分配應該通過發佈請求來防止惡意數據更改,但我並沒有真正瞭解,例如,如何修改第2行的author_id,因爲它來自Auth,而不是來自輸入。

回答

1

我認爲在這種情況下,你可以使用new ArticleComment($request->input())$comment->fill($request->input())指定用戶可輸入數據,然後分配的ID或者非用戶可編輯的數據(在你的情況下,author_id)分開。

$comment = new App\ArticleComment($request->input()); 
$comment->author_id = Auth::user()->id; 
$comment->save() 

這將阻止用戶發佈與AUTHOR_ID作爲一個字段的形式,但仍允許您快速將用戶分配領域,而不必無處不在,你需要做它列出來。

0

在你的例子中,沒有人能夠修改它。然而,如果你想分配這樣的東西呢?

ArticleComment::create($request->all()); 

現在場可以進行修改。這就是Mass Assignement的目的所在。