php - 在 laravel 雄辩的关系中寻找最高价值
问题描述
因此,我基本上是在尝试查找所选结果的值(可能会有所不同),然后根据选择的结果数量来比较它们以找到最高的特定列值。
以下是我收集结果的方式:
public function index($id = null, $name = null, $id2 = null, $name2 = null, $id3 = null, $name3 = null)
{
$users = [];
$jsonStats = [];
if (isset($id)) {
$users[] = Users::query()->findOrFail($id);
if (isset($id2)) {
$users[] = Users::query()->findOrFail($id2);
if (isset($id3)) {
$users[] = Users::query()->findOrFail($id3);
}
}
}
foreach ($users as $user) {
$jsonStats[] = $user->stats->asArray();
}
return view('frontend.index', [
'users' => $users,
'stats_json' => $jsonStats
]);
}
所以你可以看到我终于在数组中得到了一个 Eloquent 结果users[]
,尽管我需要从一个名为的关系中找到最高值stats
我试图做以下无济于事:
{{ max(array_column($users->stats, 'stat1')) }}
抛出以下内容:
试图获取非对象的属性“统计信息”
编辑
我的$user->stats->asArray();
函数返回以下内容:
public function asArray()
{
return [
'stat1' => [
[
'id' => 'attribute1',
'name' => 'Attribute1',
'type' => 'main',
'value' => $this->attr1Value
],
[
'id' => 'attribute2',
'name' => 'Attribute2',
'type' => 'main',
'value' => $this->attr2Value
],
[
'id' => 'attribute3',
'name' => 'Attribute3',
'type' => 'main',
'value' => $this->attr3Value
]
]
];
}
当试图从这个数组中找到最大值时,我尝试了以下方法:
{{ max(array_column($stats_json['stat1'][0], 'value')) }}
解决方案
由于您正在检查是否$id
已设置,因此它是可选的,并且 foreach 块将尝试访问stats
可能是的属性,因此也null
使迭代有条件
public function index($id = null, $name = null, $id2 = null, $name2 = null, $id3 = null, $name3 = null)
{
$users = [];
$jsonStats = [];
if (isset($id)) {
$users[] = Users::query()->findOrFail($id);
if (isset($id2)) {
$users[] = Users::query()->findOrFail($id2);
if (isset($id3)) {
$users[] = Users::query()->findOrFail($id3);
}
}
foreach ($users as $user) {
$jsonStats[] = $user->stats->asArray();
}
}
return view('frontend.index', [
'users' => $users,
'stats_json' => $jsonStats
]);
}
您还可以使用optional
帮助函数来避免在尝试访问非对象的属性时出错
$jsonStats[] = optional($user)->stats->asArray();
希望这可以帮助