douchu2823
2016-01-14 08:08
浏览 119
已采纳

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

I have a model that has two extra attributes which are not stored in the database, but contain request-specific information that I need. The values of these properties can be derived from the saved data inside the database, that's why they don't have their own columns in the table.

When updating this model I see it tries to pass in the declared properties in protected $attributes [...] into the update query. Can this be disabled because obviously there are no columns for my properties in $attributes array.

This is a part of my model:

<?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 ...
}

And when the update-method on the model is called I get this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert intosurvey_question_answers(0,1,label,value,index,survey_question_id,updated_at,created_at) values (labelParsed, hasOneOrMoreParameters, My custom answer label, 1, 1, 23, 2016-01-14 08:01:32, 2016-01-14 08:01:32))

As you can see it tries to put labelParsed and hasOneOrMoreParameters into the query. But I want to disable that behavior. How can this be done?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtslobe4694 2016-01-14 08:17
    已采纳

    Accessors can be used to add extra attributes to the eloquent result object.

    Model

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

    This will then be accessible like so:

    $surveyQuestionAnswer = SurveyQuestionAnswer::find(1);
    
    $labelParsed = $surveyQuestionAnswer->label_parsed;
    
    打赏 评论

相关推荐 更多相似问题