Laravel 模型在仅附加属性时嵌入嵌套模型

问题描述 投票:0回答:1

需要将计算属性附加到模型中:

class Field extends Model {
//...
    protected $appends = ['typename'];
//...
    public function getTypenameAttribute(): string {
        return $this->type->name;
    }
}

模型转储向我显示以下内容:

{
    "id": "9bc5b05b-46cf-470d-a848-cdb60aec2213",
    "name": "Показание термометра",
    "default": true,
    "twin_id": "9bc5b05b-3df3-4efd-8ce0-7a30be87af72",
    "type_id": "9bc3cea3-47e6-4ef2-a78f-347d51abbe3d",
    "created_at": "2024-04-10T07:21:36.000000Z",
    "updated_at": "2024-04-10T07:21:36.000000Z",
    "deleted_at": null,
    "origin": "thermo",
    "typename": "Целочисленное без знака",
    "type": {
      "id": "9bc3cea3-47e6-4ef2-a78f-347d51abbe3d",
      "name": "Целочисленное без знака",
      "influx_type": "uint",
      "created_at": "2024-04-09T08:54:37.000000Z",
      "updated_at": "2024-04-09T08:54:37.000000Z",
      "deleted_at": null
    }
  }

typename
计算没问题。 但我不想包含嵌套的
type
对象。我的模型类不包含任何
$with
,所以这个对象完全出乎意料。

如何从转储中排除此嵌套对象?

laravel eloquent eloquent-relationship
1个回答
0
投票

请确保您的关系模型看起来像这样

class Field extends Model {
// List of attributes to append to JSON serialization
protected $appends = ['typename'];

// List of attributes or relations to hide from JSON serialization
protected $hidden = ['type'];

// Getter for the appended attribute
public function getTypenameAttribute(): string {
    return $this->type->name;
}


public function type() {
    return $this->belongsTo(Type::class, 'type_id');
}

}

使用方法

$field = Field::find(1); //replace your id
© www.soinside.com 2019 - 2024. All rights reserved.