【问题标题】:Mass assignment working on non-fillable fields在不可填写字段上进行批量分配
【发布时间】:2014-01-17 08:30:13
【问题描述】:

我正在为一个只有两个字段的简单模型编写一些单元测试:question_id 和 title。

我已将模型上的可填充数组设置为仅包含标题:

protected $fillable = array('title');

我还创建了以下单元测试:

    /**
     * @expectedException Illuminate\Database\Eloquent\MassAssignmentException
     */
    public function testAnswerQuestionIdCanNotBeMassAssigned()
    {
        $params = ['question_id' => 1, 'title' => 'something'];
        $answer = new Answer($params);
    }

但是,没有抛出异常,导致测试失败。

我错过了什么吗?

任何建议表示赞赏。

谢谢。

【问题讨论】:

    标签: php laravel-4 eloquent mass-assignment


    【解决方案1】:

    你可以在Model的fill方法中看到原因

    public function fill(array $attributes)
    {
        $totallyGuarded = $this->totallyGuarded();
    
        foreach ($this->fillableFromArray($attributes) as $key => $value)
        {
            $key = $this->removeTableFromKey($key);
    
            // The developers may choose to place some attributes in the "fillable"
            // array, which means only those attributes may be set through mass
            // assignment to the model, and all others will just be ignored.
            if ($this->isFillable($key))
            {
                $this->setAttribute($key, $value);
            }
            elseif ($totallyGuarded)
            {
                throw new MassAssignmentException($key); <--- only if totally guarded
            }
        }
    
        return $this;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-16
      • 2020-05-02
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多