查询 laravel 从 "filled" 而非空的数据库行中获取百分比

A query for laravel to fetch percentage from the db rows which are "filled" and not empty

我们如何获取 table 中用户填写的行中字段数的百分比,以及从其他 table 行中获取父用户关系的百分比有关系。 tables

的示例

汽车table

id     name     wheels     windshields     seats
1     Hyundai    113           221           16
2       BMW      114           154           
3     Toyota                    2

如果我尝试从上面找到百分比 table 结果应该是这样的:

1 = 100% details filled
2 = 80% details filled
3 = 60% details filled

现在如果我试图让关系参与其中

车轮table

id    wheel_type        price
113     alloy            
114  chrome coated       
115     rims             946

检查汽车的关系百分比后 table 结果应该是这样的:

1 = 90% details filled
2 = 60% details filled
3 = 60% details filled

我在 Laravel 中需要做什么才能得到这样的结果

用于计算模型属性填充百分比的特征

<?php

namespace App\Models;

trait CalculatesFilledPercentage
{
    public function filled()
    {
        $attributes = collect($this->attributes);

        $totalCount  = $attributes->count();
        $filledCount = 0;

        $attributes->keys()
            ->map(function ($key) use (&$filledCount) {
                !empty($this->{$key}) ? $filledCount++ : $filledCount;
            });

        return ($filledCount / $totalCount) * 100;
    }
}

然后对于所有汽车记录

Car::all()->mapWithKeys(function($car){
    return [$car->id => "{$car->filled()}% details filled"];
});

对于关系,需要解决两种情况:

  • 有一个关系
    • 一条相关记录-比较容易算满了父子团
  • 有很多关系
    • 很多相关记录-不容易把俱乐部详细信息填满父