小编iva*_*n.c的帖子

使用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)

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

php laravel eloquent

16
推荐指数
1
解决办法
562
查看次数

标签 统计

eloquent ×1

laravel ×1

php ×1