Php 在Laravel中的模型中添加新字段

Php 在Laravel中的模型中添加新字段,php,laravel,Php,Laravel,我是拉拉维尔的初学者 作为我的模型的结果,我需要添加一个带有艺术家名称的额外字段。对于JSON和数组,我需要它 我有以下代码: public function up() { Schema::create('feature_product', function (Blueprint $table) { $table->id(); $table->foreignId('product_id')->constra

我是拉拉维尔的初学者

作为我的模型的结果,我需要添加一个带有艺术家名称的额外字段。对于JSON和数组,我需要它

我有以下代码:

public function up()
    {
        Schema::create('feature_product', function (Blueprint $table) {
            $table->id();
            $table->foreignId('product_id')->constrained('products')->onDelete('cascade');
            $table->foreignId('feature_id')->constrained('features')->onDelete('cascade');
            $table->foreignId('feature_value_id')->nullable()->constrained('feature_values')->onDelete('set null');
            $table->string('custom_value')->nullable();
            $table->timestamps();
        });
    }


Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->foreignId('product_category_id')->nullable()->constrained('product_categories')->onDelete('set null');
            $table->foreignId('image_id')->nullable()->constrained('images')->onDelete('set null');
            $table->foreignId('vat_type_id')->nullable()->constrained('vat_types')->onDelete('set null');

            $table->string('name');
            $table->string('slug');
            $table->text('lead')->nullable();
            $table->text('description');
            $table->decimal('price', 10, 2);

            $table->deactivation();
            $table->timestamps();
            $table->softDeletes();
        });
型号:

 class Product extends Model implements Presentable
{
    use SoftDeletes,
        Deactivation,
        Seoable,
        Taggable,
        Translatable,
        Imageable;

    protected $appends = array(
        'artist' => ''
    );

    protected $fillable = [
        'name',
        'slug',
        'lead',
        'description',
        'price',
        'product_category_id',
        'image_id',
        'vat_type_id'
    ];

    protected $dates = [
        'deactivated_at',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    protected $casts = [
        'image_id' => 'integer',
        'product_category_id' => 'integer',
        'vat_type_id' => 'integer',
        'min_student_level' => 'integer',
        'price' => 'decimal:2'
    ];

    protected $hidden = [
        'product_category_id',
        'image_id',
        'vat_type_id',
        'deactivated_at',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    public function image(): BelongsTo
    {
        return $this->belongsTo(Image::class);
    }

    public function productCategory(): BelongsTo
    {
        return $this->belongsTo(ProductCategory::class);
    }

    public function vatType(): BelongsTo
    {
        return $this->belongsTo(VatType::class);
    }

    public function features(): BelongsToMany
    {
        return $this->belongsToMany(Feature::class)->withPivot('feature_value_id', 'custom_value');
    }

    public function getAdminUrlAttribute(): AbstractAdminUrlPresenter
    {
        return new ProductUrlPresenter($this);
    }

    public function getPriceFormattedAttribute(): string
    {
        return Str::price($this->price);
    }

    public function getPriceNettoAttribute(): string
    {
        $priceNetto = (1 - $this->vatType->value / 100) * $this->price;
        return Str::price(max(0, $priceNetto));
    }

    public function getArtistAttribute()
    {
        $features = $this->features()->get();
        if (count($features) > 0 ) {
            foreach ($features as $feature) {
                if (isset($feature->pivot) && $feature->name == "Artysta") {
                    return $this->appends['artist'] =  $feature->pivot->custom_value;
                }
            }
        }
    }

    public function artist()
    {
        return $this->getArtistAttribute();
    }
调试模型时,我得到以下结果:

$products = $this->productRepository->getMany(['artist'])->sortBy('name');
        dd ($products);
我的结果是:

{
    "message": "Call to a member function addEagerConstraints() on string",
    "exception": "Error",
    "file": "/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php",
    "line": 586,
    "trace": [
        {
            "file": "/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php",
            "line": 564,
            "function": "eagerLoadRelation",
            "class": "Illuminate\\Database\\Eloquent\\Builder",
            "type": "->"
        },
        {
            "file": "/var/www/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php",
            "line": 532,
            "function": "eagerLoadRelations",
            "class": "Illuminate\\Database\\Eloquent\\Builder",
            "type": "->"
        },
        {
            "file": "/var/www/app/Repositories/Base/BaseRepository.php",
            "line": 84,
            "function": "get",
            "class": "Illuminate\\Database\\Eloquent\\Builder",
            "type": "->"
        },
        {
            "file": "/var/www/app/Http/Controllers/Json/ProductListController.php",
            "line": 22,
            "function": "getMany",
            "class": "App\\Repositories\\Base\\BaseRepository",
            "type": "->"
        },
        {
            "function": "list",
            "class": "App\\Http\\Controllers\\Json\\ProductListController",
            "type": "->"
        },
当我在没有“艺术家”的情况下运行代码时:

我没有错误,但附加艺术家为空:

Illuminate\Database\Eloquent\Collection {#1422 ▼
  #items: array:2 [▼
    1 => App\Models\Catalog\Product {#1447 ▼
      #appends: array:1 [▼
        "artist" => ""
      ]
      #fillable: array:8 [▶]
      #dates: array:4 [▶]
      #casts: array:6 [▶]
      #hidden: array:7 [▶]
      #connection: "mysql"
      #table: "products"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:13 [▼
        "id" => 2
        "product_category_id" => 3
        "image_id" => 1
        "vat_type_id" => 1
        "name" => "Album 2"
        "slug" => "album-2"
        "lead" => "<p>fwe</p>"
        "description" => "<p>fwe</p>"
        "price" => "54.00"
        "deactivated_at" => null
        "created_at" => "2020-10-05 11:49:22"
        "updated_at" => "2020-10-05 11:49:22"
        "deleted_at" => null
      ]
      #original: array:13 [▶]
      #changes: []
      #classCastCache: []
      #dateFormat: null
      #dispatchesEvents: []
      #observables: []
      #relations: array:3 [▶]
      #touches: []
      +timestamps: true
      #visible: []
      #guarded: array:1 [▶]
      #forceDeleting: false
    }
illumb\Database\elount\Collection{1422▼
#项目:阵列:2[▼
1=>App\Models\Catalog\Product{#1447▼
#附件:数组:1[▼
“艺术家”=>“
]
#可填充:数组:8[▶]
#日期:数组:4[▶]
#演员:阵列:6[▶]
#隐藏:数组:7[▶]
#连接:“mysql”
#表:“产品”
#主密钥:“id”
#键类型:“int”
+递增:真
#带:[]
#withCount:[]
#每页:15
+存在:正确
+最近被创建:false
#属性:数组:13[▼
“id”=>2
“产品类别标识”=>3
“图像_id”=>1
“增值税类型id”=>1
“名称”=>“相册2”
“slug”=>“专辑2”
“潜在客户”=>“fwe

” “说明”=>“fwe

” “价格”=>“54.00” “在”=>null处禁用\u “创建于”=>“2020-10-05 11:49:22” “更新时间:2020-10-05 11:49:22” “已删除”=>空 ] #原件:阵列:13[▶] #更改:[] #classCastCache:[] #日期格式:空 #调度事件:[] #可观测值:[] #关系:数组:3[▶] #触摸:[] +时间戳:真 #可见:[] #防护:阵列:1[▶] #强制删除:false }
我怎样才能修理它

怎么了


请帮助我

您需要像这样添加新的
$appends
属性

protected$appends=['artist']
公共函数getArtistAttribute()
{
$features=$this->features()->get();
如果(计数($features)>0){
foreach($features作为$feature){
如果(isset($feature->pivot)&&&$feature->name==“Artysta”){
返回$feature->pivot->custom\u值;
}
}
}
}
然后
getArtistAttribute
返回要关联的值

Illuminate\Database\Eloquent\Collection {#1422 ▼
  #items: array:2 [▼
    1 => App\Models\Catalog\Product {#1447 ▼
      #appends: array:1 [▼
        "artist" => ""
      ]
      #fillable: array:8 [▶]
      #dates: array:4 [▶]
      #casts: array:6 [▶]
      #hidden: array:7 [▶]
      #connection: "mysql"
      #table: "products"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:13 [▼
        "id" => 2
        "product_category_id" => 3
        "image_id" => 1
        "vat_type_id" => 1
        "name" => "Album 2"
        "slug" => "album-2"
        "lead" => "<p>fwe</p>"
        "description" => "<p>fwe</p>"
        "price" => "54.00"
        "deactivated_at" => null
        "created_at" => "2020-10-05 11:49:22"
        "updated_at" => "2020-10-05 11:49:22"
        "deleted_at" => null
      ]
      #original: array:13 [▶]
      #changes: []
      #classCastCache: []
      #dateFormat: null
      #dispatchesEvents: []
      #observables: []
      #relations: array:3 [▶]
      #touches: []
      +timestamps: true
      #visible: []
      #guarded: array:1 [▶]
      #forceDeleting: false
    }