php - 使用 Eloquent 保护数据透视表免受质量分配

标签 php laravel eloquent

我有下表:

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/

相关文章:

PHP 文件目录 - $_SERVER ['DOCUMENT_ROOT' ] 的父文件夹

php - 无法填充组合框选项

php - 标准 PHP 库 (SPL) 函数的时间复杂度

php - Laravel 多个多对多关系?

php - Laravel,在 Eloquent 语法中应用 where 之后 with

php - Laravel Eloquent 关系和连接多个表

php - 使用 where in 条件和最新时间​​戳连接两个 MySQL 查询

laravel - 特征 SendsPasswordResetEmails 中的broker()函数如何返回\Illuminate\Contracts\Auth\PasswordBroker?

javascript - TokenMismatchException laravel 5.3

php - 不支持完整的 REPL