模态框: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
直接在一个查询中急切加载自定义属性?