您好,我正在尝试获取每个设备的数据库中的最后一个寄存器
我喜欢
id | id_equip
-----+----------
1 | 3
2 | 3
3 | 3
4 | 2
5 | 2
我想查询每个装备的最后一个 id,例如:
id | id_equip
-----+----------
3 | 3
5 | 2
我试过这个:
$calibracao = $this->calibracao->orderBy('id', 'DESC')->groupBy('id_equip')->get();
谢谢您的帮助!
一个简单的方法, 没有join
, using max
:
$query = DB::table('equip')
->select(DB::raw('*, max(id) as id'))
->groupBy('id_equip')
->orderBy('id', 'asc')
->get();
(当然,假设您可以信赖您的id
按日期顺序排列。)
您也可以使用 Eloquent 来做到这一点,使用自引用的一对一关系。该查询需要更长的时间,但它更像 Laravel:
在模型中定义关系:
class myModel extends Eloquent {
public function latestEquipment()
{
return $this->hasOne('myModel', 'id_equip', 'id_equip')->latest();
}
}
(请注意,在本例中,我们使用latest()
这样我们就不会依赖于顺序id
s 来确定最近的条目,而是在created_at
每条记录的日期。这样更准确。)
要检索所有记录及其最新的设备条目:
$latest = myModel::with('latestEquipment')->groupBy('id_equip')->get();
// loop over the results
foreach ($latest as $l) {
if ($l->equipment) {
echo('ID: ' . $l->id . 'ID_EQUIP: ' . $l->id->id_equip . '<br>');
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)