2015-04-17 87 views
14

我有如下表:保護的數據透視表雄辯

document: id, name; 
author: id, name, job_title; 
document_author: document_id, author_id, position 

我傳遞以下結構的數組:

$attributes = [name, job_title, position]; 

我試圖創建作者的模型,並附它來文件:

$author = \Author::create($attributes); 
\Document::find($id)->authors()->save($author,$attributes); 

然後我得到QueryException,因爲laravel試圖質量分配屬性轉換爲數據透視表,而它只應通過position字段。

我得到的唯一的解決辦法是濾波器陣列,這樣的:

$author = \Author::create($attributes); 
$pivotAttributes = array_only($attributes, ['position']) 
\Document::find($id)->authors()->save($author,$pivotAttributes); 

有沒有什麼更好的辦法,確定哪些數據透視表的列是可填寫的,更好的地方在模型或在它的關係是什麼?

+0

如果'$ attributes'是'Request'(或'Input')例如,你可以做'$請求 - >只('位置');' –

回答

2

我在Laravel代碼中進行挖掘,沒有發現任何好方法,即使它是Model的子類,如何指定可透視類或可保護參數到Pivot類。

這意味着你的方法已經很不錯了。

+0

我明白了。但有沒有一種方法來擴展Eloquent以執行如下操作:'$ model-> belongsToMany(...) - > fillable(...)'? –

2

試試吧

$author = \Author::create($attributes); 
$author->documents()->attach($id,["position"=>$request->get('position')]); 

顯示文件 http://laravel.com/docs/5.0/eloquent#inserting-related-models

+0

歐普已經這麼做了 –

+0

是的。它仍然需要描述模型之外的字段。只是一個不同的角度。 –

相關問題