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

使用自定义属性更新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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号