Supplier 模型定义如下:

<?php

namespace App\Models;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;

class Supplier extends Model
{
    use HasDateTimeFormatter;

    protected $appends = [
        'name_type',
    ];

    public function getNameTypeAttribute()
    {
        return $this->name . '(' . self::$typeMap[$this->type] . ')';
    }
}

在模型中追加了一个 name_type 属性,然后即使在查询方法指定了要查询的列,返回的结果仍然带有追加的属性,比如:

public function suppliers(Request $request)
{
    return \App\Models\Supplier::get(['id','name as text']);
}

显示的结果如下,同时因为指定的列里面,没获取type,在显示追加的 name_type 属性时,还会报错。

[
{"id":1,"text":"\u4e2a\u4eba","name_type":""},
{"id":2,"text":"\u7f8e\u7684\u5b98\u65b9\u65d7\u8230\u5e97","name_type":""},
{"id":3,"text":"GREE\u683c\u529b\u5b98\u65b9\u65d7\u8230\u5e97","name_type":""}
]

这是因为追加的属性已经默认包含在查询结果中了,如果我们不想在查询结果中包含追加属性,可以使用makeHidden方法。

public function suppliers(Request $request)
{
    return \App\Models\Supplier::makeHidden('name_type')->get(['id','name as text']);
}

这样就可以在查询结果中屏蔽追加的属性了,最终结果如下:

[
{"id":1,"text":"\u4e2a\u4eba"},
{"id":2,"text":"\u7f8e\u7684\u5b98\u65b9\u65d7\u8230\u5e97"},
{"id":3,"text":"GREE\u683c\u529b\u5b98\u65b9\u65d7\u8230\u5e97"}
]
(adsbygoogle = window.adsbygoogle || []).push({});