我正在寻找在Laravel中平均子模型值的最佳方法,但忽略了一些值。我想要平均的列设置为varchar,但包含0到10之间的数字或值' N / A'。我在这个专栏中需要两个平均值,一个忽略了N / A'值和一个计数N / A'值为0.我已经写了如何计算平均值的函数,但我希望得到一些关于最佳方法的输入。
我希望能够像这样调用这些函数:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"cloudformation:DeleteStack"
],
"Resource": "*"
}
]
}
功能:
$web_scored_tq = $website->scored_tq;
$web_uscored_tq = $website->unscored_tq;
答案 0 :(得分:0)
我找到了laravel的模型getFooAttribute!我用它将以下功能添加到我的网站模型中,现在可以调用$ website-> scored_tq或$ website-> unscored_tq。
public function getScoredTqAttribute() {
$valid_click_ads = $this->valid_click_ads;
$total = 0;
$num = 0;
foreach ($valid_click_ads as $valid_click_ad) {
if ($valid_click_ad->tq != -1) {
$total += $valid_click_ad->tq;
++$num;
}
}
if ( $num != 0 ) {
$scored_tq = $total / $num;
} else {
$scored_tq = '-';
}
return $scored_tq;
}
public function getUnscoredTqAttribute() {
$valid_click_ads = $this->valid_click_ads;
$total = 0;
$num = 0;
foreach ($valid_click_ads as $valid_click_ad) {
if ($valid_click_ad->tq != -1) {
$total += $valid_click_ad->tq;
}
++$num;
}
if ( $num != 0 ) {
$unscored_tq = $total / $num;
} else {
$unscored_tq = '-';
}
return $unscored_tq;
}
我还将数据的结构更改为整数,其中“N / A”值更改为-1。