在我的数据库中,我在通知和状态表之间有很多关系。因此数据透视表存储了notification_id,statuses_id和值。现在,在我的模型中,我编写了一个函数historysStatus,它从数据透视表中提取值和created_at
public function historystatus()
{
$o_status = Status::where('name','health')->first();
$o_response = $this->statuses()->where('status_id', $o_status->id)
->select('values','created_at')->first();
if($o_response === null){
return false;
}
return ['value' => $o_response->values,
'timestamp' => $o_response->created_at];
}
我想迭代与特定notification.thus相关联的所有值和时间戳。我为每个循环编写了迭代所有值并在其中创建的。
@foreach($notes as $notification)
<?php $notificationHealth = $notes->historystatus('health'); ?>
<tr>
<td>{{ $notificationHealth['timestamp'] }}</td>
<td> {{ $notificationHealth['value'] }}</td>.
</tr>
@endforeach
</tbody>
相反,它只给了我4次最后一次记录。 sql查询有问题吗?我会很感激任何建议和想法吗?
答案 0 :(得分:0)
在foreach
内部尝试使用$notification->historystatus('health');
代替$notes->historystatus('health');
@foreach($notes as $notification)
<?php $notificationHealth = $notification->historystatus('health'); ?>
<tr>
<td>{{ $notificationHealth['timestamp'] }}</td>
<td> {{ $notificationHealth['value'] }}</td>.
</tr>
@endforeach
答案 1 :(得分:0)
public function history($s_type)
{
if (!in_array($s_type, ['speed', 'health'])){
return false;
}
$o_status = Status::where('name', strval($s_type))->first();
$o_response = $this->statuses()->where('status_id', $o_status->id)
->select('values', 'created_at')->orderBy('created_at','DESC')->get();
if($o_response === null || $o_response->count() === 0){
return false;
}
$a_ret = [];
foreach ($o_response as $o_status) {
$a_ret[] = [
'value' => $o_status->values,
'timestamp' => $o_status->created_at
];
}
return $a_ret;
}
这是我想出的简单答案。和叶片侧面的foreach环。