使用Pivot附加到BelongsToMany后需要Laravel fresh()

68bkxrlz  于 2023-05-08  发布在  其他
关注(0)|答案(1)|浏览(97)

按照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');
    }
}
kulphzqa

kulphzqa1#

您可以使用load重新加载特定关系,而不是刷新整个模型。

$subscription->products()->attach($productsToSync);

// this will mutate $subscription
// no need to do $subscription = $subscription->...
$subscription->load('products'); 

throw_if(
  $subscription->products->isEmpty(), 
  new \Exception("Products not attached to subscription WTF!?!")
);

相关问题