Php 使用Elount保护数据透视表不受质量分配的影响

Php 使用Elount保护数据透视表不受质量分配的影响,php,laravel,eloquent,Php,Laravel,Eloquent,我有以下表格: 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)-

我有以下表格:

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);

有没有更好的方法来定义pivot表的哪些列是可填充的,更好的方法是在模型中的某个地方或在它的关系中?

我在深入研究Laravel代码,我没有找到任何好的方法来指定pivot类的可填充或保护参数,即使它是模型的子类

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

试试看

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

如果
$attributes
请求
(或
输入
)实例,您可以只执行
$Request->('position')是的。它仍然需要描述模型之外的字段。只是换个角度,我明白了。但是,有没有一种方法可以扩展Eloquent,以便执行以下操作:
$model->belongsToMany(…)->filleble(…)