mysql - 对 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 中做什么才能获得这样的结果
解决方案
计算模型属性填充百分比的特征
<?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"];
});
对于关系,需要解决两种情况:
- 有一个关系
- 一项相关记录 - 相对容易计算,填满了父母俱乐部
- 有很多关系
- 许多相关记录-不容易将俱乐部详细信息填满父母
推荐阅读
- kotlin - 从 Kotlin REPL 编译和运行程序
- c++ - 2D 向量 push_back
- java - Files.copy 和 Files.write 不同,这两种方法似乎都做同样的事情,两种方法都将 Multipart 文件保存到特定位置
- android - 房间数据库关系不适用
- c# - Visual Studio 2019 的 process.MainWindowTitle 为空
- javascript - 在这种情况下如何将状态变量作为字符串传递?
- android - 错误:不兼容的类型:Intent 无法转换为 Intent[]
- c++ - C++:使用向量和迭代器时出现错误:std::bad_alloc
- c# - 使用 Asp.net/C# 使用 USB 令牌对文本文件进行数字签名?
- python - 如何在 python 正则表达式中对日期匹配应用验证