首页 > 解决方案 > 对 laravel 的查询以从“已填充”且不为空的 db 行中获取百分比

问题描述

我们如何获取表中用户填写的行中字段的百分比,以及从其他表行中获取与父用户有关系的关系百分比。表格示例

汽车表

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

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

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

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

轮子表

id    wheel_type        price
113     alloy            
114  chrome coated       
115     rims             946

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

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

我必须在 Laravel 中做什么才能获得这样的结果

标签: mysqllaravellaravel-8

解决方案


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

<?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"];
});

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

  • 有一个关系
    • 一项相关记录 - 相对容易计算,填满了父母俱乐部
  • 有很多关系
    • 许多相关记录-不容易将俱乐部详细信息填满父母

推荐阅读