使用eloquent保护数据透视表免受质量分配

时间:2021-07-12 17:03:31

I have following tables:

我有以下表格:

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

I'm passing an array of following structure:

我正在传递以下结构的数组:

$attributes = [name, job_title, position]; 

I'm trying to create author's model and attach it to document:

我正在尝试创建作者的模型并将其附加到文档:

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

Then I get QueryException, because laravel tries to mass assign attributes to pivot table, while it should only pass a position field.

然后我得到QueryException,因为laravel尝试将属性大量分配给数据透视表,而它应该只传递位置字段。

The only solution I got is to filter array, like that:

我得到的唯一解决方案是过滤数组,如下:

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

Is there any better way, to define which columns of pivot table are fillable, better somewhere in the model or in it's relation?

有没有更好的方法,定义数据透视表的哪些列是可填充的,更好地在模型中的某个位置或在它的关系中?

2 个解决方案

#1


2  

I was digging in the Laravel code and I did not find any good way how to specify fillable nor guarded parameter to Pivot class even though it is subclass of Model.

我正在挖掘Laravel代码,我没有找到任何好的方法如何为Pivot类指定可填充或保护参数,即使它是Model的子类。

This means that you approach is pretty good already.

这意味着你的方法已经相当不错了。

#2


2  

Try it

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

Show Doc http://laravel.com/docs/5.0/eloquent#inserting-related-models

显示Doc http://laravel.com/docs/5.0/eloquent#inserting-related-models

#1


2  

I was digging in the Laravel code and I did not find any good way how to specify fillable nor guarded parameter to Pivot class even though it is subclass of Model.

我正在挖掘Laravel代码,我没有找到任何好的方法如何为Pivot类指定可填充或保护参数,即使它是Model的子类。

This means that you approach is pretty good already.

这意味着你的方法已经相当不错了。

#2


2  

Try it

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

Show Doc http://laravel.com/docs/5.0/eloquent#inserting-related-models

显示Doc http://laravel.com/docs/5.0/eloquent#inserting-related-models