使用Eloquent保护数据透视表免受批量分配的影响。

17

我有以下表格:

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 尝试向 pivot 表中进行批量赋值属性,而它只应该传递一个 position 字段。

我唯一得到的解决方案是过滤数组,像这样:

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

是否有更好的方法来定义交叉表的填充列,最好是在模型或其关系中的某个地方?


如果 $attributes 是一个 Request(或 Input)实例,您可以执行 $request->only('position'); - Martin Bean
2个回答

2

是的,它仍然需要在模型之外描述字段。只是一个不同的角度。 - ivan.c

2

我在挖掘Laravel代码时,发现没有找到任何好的方法来指定填充(fillable)或保护(guarded)参数到Pivot类中,尽管它是Model的子类。

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


我明白了。但有没有一种方法可以扩展Eloquent,以便像这样执行操作:$model->belongsToMany(...)->fillable(...) - ivan.c

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接