$surrender的每个实例都有多个特性,每个特性都有不同的稀缺性,我想根据组合的
以下是我的代码
$features = $surrender->character->image->features()->get();
foreach($features as $traits) {
$rarity = Rarity::where('id', $traits->rarity_id)->first();
switch($rarity->name) {
// e.g if the rarity name returns rare, the cost is 100
case 'rare':
$cost = 100;
break;
}};
$totalcost = collect($cost)->sum();
}
else $totalcost = NULL;但是,当我有稀有“稀有”的两个特性时,这只返回100。
如何修改代码以使其正常工作?
发布于 2020-10-29 22:24:26
您在每个循环中都使用相同的值:
$cost = 100;为了得到你的总结,你可以简单地累积成本:
$cost += 100;将其应用于您的代码片段:
$features = $surrender->character->image->features()->get();
$totalCost = 0;
foreach ($features as $traits) {
$rarity = Rarity::where('id', $traits->rarity_id)->first();
switch ($rarity->name) {
// e.g if the rarity name returns rare, the cost is 100
case 'rare':
$totalCost += 100;
break;
}
}发布于 2020-10-30 04:30:45
问题已经有了一个选定的答案。
如果有人对重构代码感兴趣,可以使用laravel collection方法。
$totalCost = $surrender->character->image->features->sum(function($feature) {
return Rarity::where('id', $traits->rarity_id)->where('name', 'rare')->exists() ? 100 : 0;
});将成为更有效的
前一种方法的问题是,将有多个数据库调用来获取每个feature的feature。为了避免这种情况,我们可以急切地加载rare。
在rarity()模型中定义Feature关系
public function rarity()
{
return $this->bgelongsTo(Rarity::class);
}现在在财务总监
$features = $surrender->character->image->features()->with('rarity')->get();
$totalCost = $features->sum(function($feature) {
return $feature->rarity->name == 'rare' ? 100 : 0;
});另一种方法
我想你只是想总结一下“稀有特征”的稀缺性。然后,让我们只获取一些罕见的特性。
$rarefeatures = $surrender->character->image->features()
->whereHas('rarity', function($query) {
return $query->name('name', 'rare');
})->get();
$totalCost = $rareFeatures->sum(function($feature) {
return 100;
});另一种方法
似乎我们甚至都不想获取“稀有特征”。我们只需要统计一下“稀有特征”。
$rareFeaturesCount = $surrender->character->image->features()
->whereHas('rarity', function($query) {
return $query->name('name', 'rare');
})->count();
$totalCost = 100 * $rareFeaturesCount;https://stackoverflow.com/questions/64599890
复制相似问题