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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?