【问题标题】:Query to get the previous element related to the id in Laravel Eloquent在 Laravel Eloquent 中查询获取与 id 相关的上一个元素
【发布时间】: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()

标签: laravel eloquent


【解决方案1】:

试试这个一定可以的

$pos->devices()->newPivot()->where([ ['device_id', '<', $this->id], ['pos_id','=', $this->pos_id] ])->max('device_id');

或者你可以使用

DevicePos::where([
    ['device_id', '<', $this->id],
    ['pos_id','=', $this->pos_id]
])->max('device_id');

查看相关https://laravel.com/docs/5.5/queries#aggregates

DB 外观示例

DB::table('devices_pos')->where([
        ['device_id', '<', $this->id],
        ['pos_id','=', $this->pos_id]
    ])->max('device_id');

【讨论】:

  • 问题是当我在原始 SQL 上进行查询时它可以工作,但这样我只会得到 NULL。
  • 还要检查$this-&gt;pos_id 的值吗?这是什么??
  • pos_id的值为7
  • $this->id 值??
  • 为了测试首先使用 Device::max('device_id');
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-09
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
  • 2013-12-14
  • 2021-05-25
  • 1970-01-01
相关资源
最近更新 更多