简体   繁体   English

Laravel 5.3 $附加不起作用

[英]Laravel 5.3 $appends not working

Below is the code for model 下面是模型的代码

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $appends = [
        "desc"
    ];

    protected $fillable = ['id'];

    public function getDescAttribute()
    {
        return strip_tags( $this->attributes['description'] );
    }
}

So now when i do 所以现在当我这样做

$product = Product::first();

It doesn't return desc field in the $product, though when i do $product->desc it returns the result, but i want that result to be appended in the model itself. 它不返回$ product中的desc字段,但是当我执行$ product-> desc时它会返回结果,但我希望将结果附加到模型本身中。

The following code gives me error 以下代码给出了错误

$product = Product::first()->get(['desc']);

It runs 它运行

Select desc from products...

But as the desc is not there i am getting error. 但由于desc不在那里我得到错误。

Is anything I'm doing wrong? 我做错了什么吗?

Fields that you add to $appends array are only appended when object is serialized to array/JSON . 只有在将对象序列化为array / JSON时,才会附加添加到$ appends数组的字段。 Otherwise it doesn't make sense to define this attribute until it's really needed - that's why you're getting the value when you access $product->desc . 否则,在真正需要之前定义此属性是没有意义的 - 这就是您在访问$ product-> desc时获取值的原因。 It's done to save unnecessary operations - calculating the value of a custom attribute could involve some heavy operations and is delayed till it's really needed. 这样做是为了节省不必要的操作 - 计算自定义属性的值可能涉及一些繁重的操作,并且会延迟到真正需要的时候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM