使用自定义属性更新Eloquent模型


Updating an Eloquent model with custom attributes

我有一个模型,它有两个额外的属性,这些属性没有存储在数据库中,但包含我需要的特定于请求的信息。这些属性的值可以从数据库中保存的数据中派生,这就是为什么它们在表中没有自己的列。

当更新这个模型时,我看到它试图将protected $attributes [...]中声明的属性传递到更新查询中。这可以被禁用吗,因为显然在$attributes数组中没有用于我的属性的列。

这是我模型的一部分:

<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
use Illuminate'Support'Facades'DB;
/**
 * Class SurveyQuestionAnswer
 * @package App
 */
class SurveyQuestionAnswer extends Model
{
    /**
     * @var array
     */
    protected $fillable = ['label', 'value', 'index'];
    protected $attributes = ['labelParsed', 'hasOneOrMoreParameters'];
    // more model code ...
}

当调用模型的更新方法时,我会得到以下错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into survey_question_answers ( 0 , 1 ,标签,,索引, surve_question_id ,更新,创建) values (labelParsed, hasOneOrMoreParameters, My custom answer label, 1, 1, 23, 2016-01-14 08:01:32, 2016-01-14 08:01:32))

正如您所看到的,它试图将labelParsedhasOneOrMoreParameters放入查询中。但我想禁止这种行为。如何做到这一点?

访问器可用于为雄辩的结果对象添加额外的属性。

型号

public function getlabelParsedAttribute()
{
    return 'some value';
}

这样就可以访问:

$surveyQuestionAnswer = SurveyQuestionAnswer::find(1);
$labelParsed = $surveyQuestionAnswer->label_parsed;