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

时间:2016-01-14 08:08:55

标签: php laravel model attributes eloquent

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

更新此模型时,我看到它尝试将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 ...
}

当调用模型上的update-method时,我收到此错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into survey_question_answers {{1} {0 {1}} 1 (标签,的值,索引, survey_question_id ,的updated_at , {created_at {1}}

正如您所看到的,它会尝试将,,放入查询中。但我想禁用这种行为。怎么办呢?

1 个答案:

答案 0 :(得分:1)

Accessors可用于向eloquent结果对象添加额外属性。

模型

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

然后可以这样访问:

$surveyQuestionAnswer = SurveyQuestionAnswer::find(1);

$labelParsed = $surveyQuestionAnswer->label_parsed;
相关问题