【问题标题】:Changing an attibute of Laravel Eloquent collection changes every reference更改 Laravel Eloquent 集合的属性会更改每个引用
【发布时间】:2021-10-27 06:00:36
【问题描述】:

这是我的场景。 我在订阅和产品之间有关系。每个订阅都属于某个产品,我已经定义了关系。

现在,如果我这样做: Subscription::with(['product', 'address'])->get(); 我将获得产品的所有订阅。

产品具有 shipping_price、price 等属性。

现在,如果我在订阅中更改产品的 shipping_price,它会在所有订阅中更改该产品的 shipping_price(这很方便,但这次我不希望这种更改无处不在)。

例如:

$subscriptions = Subscription::with('product')->get();
foreach ($subscriptions as $item) {
   $item->product->shipping_price = ShippingService::getShippingPrice($item->product->key, $item->product->shipping_price, $item->address->zip);
}

这将更改这些订阅中具有相同 ID 的每个产品的 shipping_price。

我的要求是在这个地方停止这种行为。所以如果我改变一个属性,它不会改变其他属性。

我知道一种使用循环再次查询的方法,并且不会使用急切加载来获取产品,但这会很慢。

谢谢。

【问题讨论】:

  • 如果你有一个条件属性,你为什么不拉起订阅上的 shipping_price 并返回 $item->product->shipping_price 在同一个 getter 中你可以添加一个调用有条件的,看看你想要产品的 shipping_price 还是你自己的
  • 您能否包含一个示例条件,可以是 if ($subscription->type === 'sub1') {} 吗?
  • @mrhn 是的。其实我没有确切的条件。我有一个返回运费的函数,然后我更新了这个属性。例如,$item->product->shipping_price = somefunction(parameters); 但它会在每次订阅时更改该产品的 shipping_price。
  • @mrhn 我已经更新了那部分。

标签: php laravel eloquent collections


【解决方案1】:

我将使用访问器 getRealShippingPriceAttribute(使用您的 ShippingService)向此产品模型添加自定义属性“real_shipping_price”。

例如,请参阅https://laravel.com/docs/5.3/eloquent-serialization#appending-values-to-json

【讨论】:

  • 考虑我有一个与模型无关的参数。那我该怎么做呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-24
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
  • 2021-11-24
  • 2012-06-09
  • 2021-11-20
相关资源
最近更新 更多