gpt4 book ai didi

php - 如何通过 Laravel 5 中的 SQL 查询在模型中分配动态属性

转载 作者:行者123 更新时间:2023-11-29 03:22:23 25 4
gpt4 key购买 nike

我正在使用 Laravel 5.3 构建 API,并且我有一个产品模型。每当我检索产品时,我都想检索产品的评级和推荐费率。我还有一个评论模型,产品有很多评论。

$product = Product::where('slug', $slug)->with('reviews')->first()->toArray();

评分的计算方法是在 Controller 中循环 $product->reviews,将每条评论的分数相加,然后除以评论总数。

if (count($product['reviews']) > 0) {
$i = 0;
$totalScore = 0;
foreach ($product['reviews'] as $review) {
$totalScore = $totalScore + $review['Rating'];
$i++;
}
$product['averageReviewRating'] = $totalScore / $i;
} else {
$product['averageReviewRating'] = null;
}

建议的费率是使用 SQL 查询计算得出的。

$product['recommendedRate'] = round(DB::select("
select ( count ( if (Recommend = 1,1,NULL) ) / count(*)) * 100 as rate
from Review where PrintProduct_idPrintProduct = " . $product['idPrintProduct']
)[0]->rate);

这给我留下了 $product['averageReviewRating'] 和 $product['recommendedRate'] 我想要的数据,但看起来非常草率。我希望能够做类似于下面的事情,并将这两个值分配给集合的每个对象,而不是通过 $product->averageReviewRating$product->recommendedRate 或者甚至不将它们包含在 with 中并急切地分配这些值。

$product = Product::where('slug', $slug)->with(['Reviews', 'RecommendedRate', 'AverageReviewRating'])->first();

有人知道用 ORM 做这个的方法吗?我四处寻找,没有找到任何东西。

最佳答案

你可以这样做

protected $appends = [
'reviews',
'recommendedRate',
'averageReviewRating'
];

public function getReviewsAttribute() {
return $this->reviews()->get();
}

public function getRecommendedRateAttribute() {
if (count($this->reviews) > 0) {
$i = 0;
$totalScore = 0;
foreach ($this->reviews as $review) {
$totalScore = $totalScore + $review->Rating;
$i++;
}
return $totalScore / $i;
} else {
return null;
}
}

public function getAverageReviewRatingAttribute() {
return round(DB::select("
select ( count ( if (Recommend = 1,1,NULL) ) / count(*)) * 100 as rate
from Review where PrintProduct_idPrintProduct = " . $this->idPrintProduct
)[0]->rate);
}

然后只需调用 Product::where('slug', $slug)->first()->toArray();

P.S. 这只是你可以做的方式,我可能会遗漏部分逻辑或名称..

关于php - 如何通过 Laravel 5 中的 SQL 查询在模型中分配动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42011823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com