【问题标题】:Laravel Eloquent - $fillable is not working?Laravel Eloquent - $fillable 不起作用?
【发布时间】:2014-05-30 00:08:48
【问题描述】:

我在我的模型中设置了变量$fillable。我想测试update 功能,我得到了这个错误:

SQLSTATE[42S22]:未找到列:1054 '字段列表'中的未知列 '_method'(SQL:更新 positions 设置 name = 休闲水族领袖,_method = PUT,id = 2 , description = 这是我的描述,updated_at = 2014-05-29 17:05:11 其中positions.client_id = 1 和id = 2)"

当我的可填充项没有它作为参数时,为什么要对 _method 大喊大叫?我的更新功能是:

Client::find($client_id)
        ->positions()
        ->whereId($id)
        ->update(Input::all());

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    更改以下内容:

    ->update(Input::all());
    

    对此(从数组中排除_method

    ->update(Input::except('_method'));
    

    更新:

    实际上是从_call 类的Illuminate\Database\Eloquent\Relations 方法触发的Illuminate\Database\Eloquent\Builder 类调用update 方法(因为您在关系上调用update),因此$fillable没有执行检查,您可以使用Input::except('_method'),正如我回答的那样:

    public function update(array $values)
    {
        return $this->query->update($this->addUpdatedAtColumn($values));
    }
    

    如果您直接在模型上调用它(而不是在关系上):

    Positions::find($id)->update(Input::all());
    

    那么这将不会发生,因为fillable 检查将在Model.php 内执行,因为将从Illuminate\Database\Eloquent\Model 类调用以下update 方法:

    public function update(array $attributes = array())
    {
        if ( ! $this->exists)
        {
            return $this->newQuery()->update($attributes);
        }
    
        return $this->fill($attributes)->save();
    }
    

    【讨论】:

    • 这是我最初的测试邮递员。实际上,我还有很多其他密钥正在发送。这个$fillable 的全部意义在于我不必这样做!
    • 你是如何使用/设置fullable属性的?它在哪里?
    • 在我的模型文件中我有protected $fillable = array('name', 'show_order', 'description');
    • 您的模型中是否还声明了$guarded 属性?
    • 不,我没有。我需要吗?
    【解决方案2】:

    写一个父类

    class BaseModel extends Model
    
    public static function getFillableAttribute(Model $model, $data){
        $array = $model->getFillable();
        $arr = [];
        foreach ($array as $item){
            if( isset($data["$item"])){
                $arr["$item"] = $data["$item"];
            }
        }
        return $arr;
    }
    

    【讨论】:

      【解决方案3】:

      我在从 Laravel 5.2 更新到 5.4 后遇到了这个问题 - 我在文档/迁移指南中找不到任何内容。

      正如github issue 中所述,Eloquent 的正确修复/使用似乎是:

      Positions::find($id)->fill(Input::all())->save();
      

      通过 laravel 触发 fillable 检查,然后持久化更改。

      【讨论】:

        【解决方案4】:

        你也可以这样做

        $data = request()->all();
        //remove them from the array
        unset($data['_token'],$data['_method']);
        //then
        Client::find($client_id)
                ->positions()
                ->whereId($id)
                ->update($data);
        
        

        这会从数组中删除 _method_token

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-01-21
          • 2012-12-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-21
          相关资源
          最近更新 更多