我有下表:
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);
有没有更好的方法来定义数据透视表的哪些列是可填充的,在模型或关系中的某个地方更好?
最佳答案
我正在研究 Laravel 代码,但我没有找到任何如何为 Pivot 类指定可填充或 protected 参数的好方法,即使它是 Model 的子类。
这意味着你的方法已经很不错了。
关于php - 使用 Eloquent 保护数据透视表免受质量分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29699132/