考虑以下模型对象:
App\Modules\CharacterSheets\Models\CharacterSheet {#826
...
#attributes: array:39 [
"id" => 1
"user_id" => 1
"race_id" => 1
"class_id" => null
"strength" => 35
"dexterity" => 35
"agility" => 55
"intelligence" => 30
"health" => 120
"haste" => 0
"precision" => 0
"dodge" => 0
"crit" => 0
"steal_health" => 5
"gold" => 0
"deffense" => 7
"damage" => 10
"cast_damage" => 10
"antique_damage" => 0
"heal_for" => 10
"level" => 1
"train_exp" => 0
"level_exp" => 200
"location" => "0, 0"
"next_level_exp" => 1000
"next_train_level_exp" => 300
"max_level" => 500
"armor_class" => 17
"block_bonus" => 3
"hit_bonus" => 2
"has_to_train" => 0
"primary_attack_stat" => "health"
"primary_attack_bonus" => "2.00"
"penalty_stat" => null
"penalty" => null
"damage_subtraction" => null
"chance_to_attack_twice" => null
"created_at" => "2019-02-16 01:26:04"
"updated_at" => "2019-02-16 01:56:42"
]
...
}
我想动态做的是检查下列哪个统计数据最高:strength
,dexterity
,agility
,intelligence
,health
我想保持对象不变,但返回属性名称作为字符串
所以例如对于上面的对象,我应该有返回health
的函数。
同样,这必须是动态的。
我没有看到任何laravel收集方法可以做到这一点,所以我在这里问,因为我不知道如何做到这一点。
从模型中提取属性并查找最大值键。
function getHighestProperty(Model $model, array $keys): string
{
$filter = array_flip($keys);
$array = collect($model->toArray());
return $array->intersectByKeys($filter)->sort()->flip()->last();
}
虽然我没试过,但我会这样做的:
首先,我们将创建一个我们想要的属性数组。
$array = [
'strength', 'dexterity', 'agility', 'intelligence', 'health',
];
接下来,创建结果集合以存储上述$array
中可用的工作表数据。
$result = collect();
循环工作表并检查上述数组中是否存在该键。如果它存在,我们将把它放在$result
集合中。
foreach ($characterSheet as $key => $sheetAttribute) {
if (in_array($key, $array)) {
$result->put($key, $sheetAttribute);
}
}
然后我们可以使用$result
方法对sort集合进行排序,以便为我们提供最小值及其键。然后你可以flip它,以便得到与该值相关的关键并返回last元素,因为你想要最大值。
$result->sort()->flip()->last();
然后你可以简单地dd($result)
并交叉验证这是否是你想要的。
首先,制定逻辑。在这种情况下,我们将使用Laravel Collections:
// CharacterSheet.php
public function highestProperty()
{
// temporal variable
$temp = collect();
// populating the temporal variable
collect(['strength', 'dexterity', 'agility', 'intelligence', 'health'])
->each(function ($property) use ($temp) {
return $temp->put($property, $this->$property);
});
// searching the property of the highest value
return $temp->search(
// getting the highest value
$temp->reduce(function ($highest, $value) {
return ($highest < $value) ? $value : $highest;
})
);
}
然后,创建一个accessor,所以你可以做$characterSheet->highest_property
:
// CharacterSheet.php
public function getHighestPropertyAttribute()
{
return $this->highestProperty();
}
你甚至可以append这个值到每个CharacterSheet
实例添加到$appends
模型配置的值:
// CharacterSheet.php
$appends = ['highest_property'];
现在,无论何时获得CharacterSheet
的实例,您都可以像使用任何其他属性一样使用它:
$characterSheet = CharacterSheet::first();
dd($characterSheet->highest_property);
// this could output, if the case: "dexterity"