【问题标题】:Protect pivot table from mass assignment using eloquent使用 eloquent 保护数据透视表免受批量分配
【发布时间】: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);

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

【问题讨论】:

  • 如果$attributesRequest(或Input)实例,您可以使用$request->only('position');

标签: php laravel eloquent


【解决方案1】:

试试看

$author = \Author::create($attributes);
$author->documents()->attach($id,["position"=>$request->get('position')]);

显示文档 http://laravel.com/docs/5.0/eloquent#inserting-related-models

【讨论】:

  • 是的。它仍然需要描述模型之外的字段。只是视角不同。
【解决方案2】:

我正在挖掘 Laravel 代码,但我没有找到任何好的方法来指定 Pivot 类的可填充或受保护参数,即使它是 Model 的子类。

这说明你的方法已经很不错了。

【讨论】:

  • 我明白了。但是有没有办法扩展 Eloquent 以执行以下操作:$model->belongsToMany(...)->fillable(...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 2019-03-05
相关资源
最近更新 更多