Laravel动态可填充模型

Web*_*ent 3 php models eloquent laravel-5.2

在laravel 5.2中遇到了问题.

以下是eloquent创建操作(后调用)期间的错误,

Model.php 453中的批量分配异常:column_name

以下是要考虑的先决条件:

  1. 通过以下代码以动态方式填充模型中的可填充内容:
    public function __construct() {
         $this->fillable(\Schema::getColumnListing($this->getTable()))
    }
    

以下是到目前为止调试的方法:

  1. 在插入之前,在控制器中,$ model :: getillableField()给出了适当的可填充数组.

  2. 在model.php行(450)中,

    if ($this->isFillable($key)) {
          $this->setAttribute($key, $value);
    }
    

    上面的代码返回值为"false",$ model :: getFillableField()在数组列表中有column_name.

  3. 用表格列硬编码$ fillable变量会删除错误.请帮忙,我哪里出错了,解决方案是什么?

提前致谢.

Agm*_*her 6

你真正想做的是让所有字段都可填写.

在Laravel中执行此操作的正确方法是:

protected $guarded = [];
Run Code Online (Sandbox Code Playgroud)

这适用于5.2,即使它的文档在5.3中找到.

(5.2的相关源代码)

(5.3的文件):

如果您想使所有属性都可以分配,您可以将$ guarded属性定义为空数组:

通过设置$guarded为空数组,您将创建一个空的黑名单,允许所有字段都可以进行质量分配.

另外,如果这种模式永远会直接从用户输入构造,请不要这样做.Laravel要求要么$fillable$guarded的一个原因被定义.除非您的模型具有字面上1:1的公共表单字段,否则允许所有字段在批量分配上可写是一个安全漏洞.


sug*_*una 5

试试这个.将以下代码放入您的模型中,

public function __construct()
{
    $this->setFillable();
}
public function setFillable()
{
    $fields = \Schema::getColumnListing('table_name_here');

    $this->fillable[] = $fields;
}
Run Code Online (Sandbox Code Playgroud)

这使得每个列都可以从该表中填充.


kej*_*ion 5

创建一个使用数据库列的特征。

<?php

namespace App\Traits;

use Illuminate\Support\Facades\Schema;

trait ColumnFillable
{
    public function getFillable()
    {
        return Schema::getColumnListing($this->getTable());
    }
}
Run Code Online (Sandbox Code Playgroud)

现在在你的模型中使用这个特性。

<?php

namespace App;

use App\Traits\ColumnFillable;

class MyModel extends Model
{
    use ColumnFillable;

    ...
Run Code Online (Sandbox Code Playgroud)

现在您将永远不必手动指定$fillable.

  • 确保您知道这会影响数据库。也许每次模型初始化时。 (2认同)