因此,我基本上尝试查找所选结果的值(可能会有所不同),然后对它们进行比较,以根据选择的结果数量找到最高的特定列值。
以下是我收集结果的方法:
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
]);
}
正如您所看到的,我最终在 users[]
数组中得到了 Eloquent 结果,尽管我随后需要从名为 stats
的关系中找到最高值
我尝试执行以下操作但无济于事:
{{ max(array_column($users->stats, 'stat1')) }}
抛出以下内容:
Trying to get property 'stats' of non-object
编辑
我的 $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')) }}
最佳答案
首先我们得到 Laravel eloquent 关系查询。 例如:
'$data' => [
[
'id' => '1',
'name' => 'subject1',
'type' => 'T',
'value' => $this->Value
],
[
'id' => '2',
'name' => 'subject2',
'type' => 'M',
'value' => $this->Value
],
[
'id' => '3',
'name' => 'subject2',
'type' => 'T',
'value' => $this->Value
]
]
我们可以获得像这样的最大值
$max1 = max(array_column($data, 'value')) // only get value max
foreach ($data as $array) {
if (in_array($array['value'],$max1)) {
return $array;
}
}
That return value is the highest value in laravel eloquent relationship
关于php - 寻找 Laravel Eloquent 关系中的最高值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58670849/