【问题标题】:Save additional data on model-creation保存有关模型创建的其他数据
【发布时间】:2025-12-04 12:45:01
【问题描述】:

我遇到了以下问题:

我需要在我的控制器中保存一个名为InvoicePositionProduct 的项目。每个Product 可以有ProductAttributes

虽然我使用的是Product-Class,但我将此产品作为关系保存在数据库中,但我使用此类来“规范化”输入。实际上,数据进入数据库中的 JSON 字段。

所以:

发票位置

- id (incr.)
- customer_id (integer)
- quantity (integer)
- product (JSON)

为了在我的控制器中保存这个位置,我这样做:

<?php
$product = new Product($position['product']);

$invoice->positions()->create([
    'quantity'           => $position['factor'],
    'product'            => $product,
]);

这很好用。为了稍后获取Product,我使用了这个访问器:

public function getProductAttribute($value)
{
    $value                     = (array)json_decode($value);
    $product                = new Product($value);
    $product                = $product->with('productAttributes')
        ->first();
    return $product;
}

这也可以正常工作 - 我得到了一个 App\Product 的实例:

=> App\Product {#1228
     id: 1,
     price: 1.99,
     productAttributes: [...]

现在我遇到了一个问题:我需要在产品的 JSON 字段中保存附加信息。就我而言,我需要复制每个ProductproductAttributes

所以我在控制器中想到了这样的东西:

<?php
$product = new Product($position['product']);

$product->productAttributes()->map(function($attribute){
  $attribute->original = $attribute;
  return $attribute;
});

$invoice->positions()->create([
    'quantity'           => $position['factor'],
    'product'            => $product,
]);

但现在我的访问器没有反映这些更改,因为 App\Product 包含 App\ProductAttribute 但不包含附加字段。

【问题讨论】:

    标签: laravel eloquent laravel-7


    【解决方案1】:

    我想你正在寻找Observer

    class ProductObserver
    {
        // performed when product is updated
        // alternatively, use saved(Product $product), or both (depending on what you're after)
        public function updated(Product $product) 
        {
            // duplicate your product attributes here
        }
    }
    

    【讨论】:

    • 问题是,即使存储为 JSON,也不会使用访问器返回附加值。
    • @SPQRInc 你把它添加到你模型上的$fillable了吗?
    • 是的,但没有任何成功。