按照Laravel文档(和Laravel attach pivot to table with multiple values),如果不调用顶级模型上的fresh()
,我无法看到附加值。有没有更好的方法来连接这些模型?
我不想刷新整个模型,因为已经加载了其他关系。这样做会导致重新查询、示例化和开销。
附着
$productsToSync = $productsCollection->mapWithKeys(fn ($subscriptionProduct) => [
$subscriptionProduct->id => [
'quantity' => $subscriptionProduct->quantity,
'amount' => $subscriptionProduct->amount,
'item_id' => $subscriptionProduct->item_id,
]
])->toArray();
$subscription->products()->attach($productsToSync);
// This exception passes and is NOT thrown --> SubscriptionProducts are in the DB
throw_unless(
SubscriptionProducts::whereSubscriptionId($subscription->id)->count() > 0,
new \Exception("No SubscriptionProducts in DB?!)
);
// required NOT to throw ... but it refreshes and subsequently requires re-querying
// any already loaded relationships
// $subscription = $subscription->fresh();
throw_if(
$subscription->products->isEmpty(),
new \Exception("Products not attached to subscription WTF!?!")
);
订阅类
class Subscription extends Model {
public function products(): BelongsToMany
{
return $this->belongsToMany(Products::class, 'subscription_products', 'subscription_id', 'product_id')
->using(SubscriptionProduct::class)
->as('subscriptionProducts')
->withPivot('id', 'item_id', 'quantity', 'amount');
}
}
1条答案
按热度按时间kulphzqa1#
您可以使用
load
重新加载特定关系,而不是刷新整个模型。