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