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

iva*_*n.c 16 php laravel eloquent

我有以下表格:

document: id, name;
author: id, name, job_title;
document_author: document_id, author_id, position
Run Code Online (Sandbox Code Playgroud)

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

$attributes = [name, job_title, position]; 
Run Code Online (Sandbox Code Playgroud)

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

$author = \Author::create($attributes);
\Document::find($id)->authors()->save($author,$attributes);
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Mar*_*ala 2

我正在深入研究 Laravel 代码,但没有找到任何好方法来为 Pivot 类指定可填充或受保护的参数,即使它是 Model 的子类。

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