【发布时间】:2019-03-13 03:27:57
【问题描述】:
我有两张桌子。一个是设备,另一个是多对多关系中的 POS。我需要的是从我正在寻找的 POS id 中获取所有设备,但获取以前的设备,而不是最新的设备。我想在我的模型上使用它作为一个函数,以便在设备上轻松访问该元素。
Device
--------
- id
- other elements
- pos_id
- function to get the previous device for the above pos_id
POS
--------
- id
- other stuff
Devices_pos
----------
- device_id
- pos_id
我知道我可以访问 $pos->devices 并获取所有元素。
我试过了:
public function scopePrev_dev_pos()
{
if ($this->pos_id > 0){
$pos = Pos::find($this->pos_id);
return $pos->devices->where('device_id', '<', $this->id)->max('device_id');
} else {
return null;
}
}
它给我的只是一个 Eloquent Builder,里面显然没有任何东西。
查询应该是这样的:
SELECT MAX(device_id) FROM devices_pos
WHERE pos_id = 7
AND device_id < 7035;
... 但是使用 Eloquent。 id 只是一个例子。
编辑:最终使用了访问器:
public function getPreviousDeviceAttribute()
{
if ($this->pos_id > 0){
$pos = Pos::find($this->pos_id);
$prev = DB::table('devices_pos')->where('device_id', '<', $this->id)
->where('pos_id', $this->pos_id)
->max('device_id');
$device = Device::find($prev);
return $device;
} else {
return null;
}
}
我没有回答这个问题,因为我使用的是外观而不是 Eloquent,但这是一个很好的解决方法。本地范围对我的问题没有用(如果您需要测试 null 它将不起作用)。
【问题讨论】:
-
查看使用的更新答案
newPivot()