【发布时间】:2015-06-24 07:13:01
【问题描述】:
我有以下表格:
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);
有没有更好的方法来定义数据透视表的哪些列是可填充的,更好地在模型的某个地方或在它的关系中?
【问题讨论】:
-
如果
$attributes是Request(或Input)实例,您可以使用$request->only('position');