如何在 Laravel Filament 中获取数据透视表列的总和?

huangapple go评论63阅读模式
英文:

How to get the sum of a pivot table column in Laravel Filament?

问题

我的Workshop模型与User模型有这样的关系,user_workshop是中间表。

{
    返回$ this- > belongsToMany(User :: class,'user_workshop')
    - > withPivot('num_attending','price','paid_at');
}

我想获得已售出的位置(名额)数量。用户可以购买1或2个名额。在Filament表中,我正在尝试

- >sum('users','user_workshop.num_attending')

这会产生这个查询

选择'研讨会'。*,(选择sum('user_workshop.num_attending') from 'users'内部连接'user_workshop'on'users'.'id'='user_workshop'.'user_id' where'workshops'.'id'='user_workshop'.'workshop_id' and'users'.'deleted_at'为null)作为'users_sum_users_workshopnum_attending' from 'workshops'where'workshops'.'event_id'= 3和'workshops'.'event_id'不为空限制10偏移0

当我直接查询数据库时,在'users_sum_users_workshopnum_attending'下我得到了正确的结果。

在Filament中我正在尝试这样做(但列是空白的)

TextColumn::make('users_sum_users_workshopnum_attending')
          - >sum('users','user_workshop.num_attending')
          - >label('已售出'),

有什么建议吗?

英文:

My Workshop model has this relationship to User model. user_workshop being the pivot table.

public function users(): BelongsToMany
  {
    return $this->belongsToMany(User::class, 'user_workshop')
    ->withPivot('num_attending', 'price', 'paid_at');
  }

I would like to get number of places (spots) sold. A user can buy 1 or 2 spots. In Filament table I'm trying to

->sum('users', 'user_workshop.num_attending')

This produces this query

select `workshops`.*, (select sum(`user_workshop`.`num_attending`) from `users` inner join `user_workshop` on `users`.`id` = `user_workshop`.`user_id` where `workshops`.`id` = `user_workshop`.`workshop_id` and `users`.`deleted_at` is null) as `users_sum_users_workshopnum_attending` from `workshops` where `workshops`.`event_id` = 3 and `workshops`.`event_id` is not null limit 10 offset 0

And I get the correct result under users_sum_users_workshopnum_attending when I'm quering the database directly.

In Filament I'm trying this (but the column is blank)

TextColumn::make('users_sum_users_workshopnum_attending')
          ->sum('users', 'user_workshop.num_attending')
          ->label('Sold'),

Any ideas?

答案1

得分: 1

显示表格中关系的计数,您可以使用 ->counts()

TextColumn::make('users_sum_num_attending')->sum('users', 'num_attending'),

更多详细信息,请查看 Filament Column Relationship

英文:

To display a count of relationships in the table, you can use ->counts()

TextColumn::make('users_sum_num_attending')->sum('users', 'num_attending'),

for more details, you can check the Filament Column Relationship

huangapple
  • 本文由 发表于 2023年6月5日 05:50:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76402541.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定