模态:Subscription.php
class Subscription extends Model {
use HasFactory;
public function payments(): HasMany {
return $this->hasMany(SubscriptionPayment::class, 'sub_id');
}
public function totalDurationDays(): Attribute {
return Attribute::make(
get: fn() => $this->payments()->sum('duration_days')
)->shouldCache();
}
}
控制器:SubscriptionController.php
$subs = SharedServer::from('subscriptions AS ss')
->select(
'ss.*',
DB::raw("(SELECT SUM(duration_days) FROM subscription_payments AS ssp WHERE ssp.sub_id = ss.id) AS total_duration_days"),
)
->paginate();
如果从自定义属性调用
total_duration_days
,与直接从控制器调用相比,Laravel 调试栏会显示太多查询。
有没有一种方法可以指示查询构建器直接在一个查询中立即加载
total_duration_days
自定义属性?
如果您想使用totalDurationDays方法作为自定义属性并避免多次查询,则需要立即加载付款关系。这样,可以从加载的付款集合中计算总和,而不是针对每个订阅模型进行额外的查询。
在你的 subscriptioncontroller.php 中
// Eager load payments relationship
$subs = SharedServer::from('subscriptions AS ss')
->with('payments')
->paginate();`