【问题标题】:Laravel Eloquent get last pivot record within Model methodLaravel Eloquent 获取模型方法中的最后一个数据透视记录
【发布时间】:2016-10-21 09:50:37
【问题描述】:

如题,有没有可能达到这样的效果?

class Sign extends Eloquent
{
   public function lastStatus()
   {
      return $this->belongsToMany(Status::class)
                  ->withPivot('timestamp')
                  ->orderBy('timestamp', 'desc')
                  ->take(1);
   }
}

signstatus 之间存在多对多关系,我有数据透视表 sign_statussign_status 中的每个赋值都有它的timestamp,所以我可以得到关于最后状态的信息,但是如何在 Model 方法中实现呢?

有必要这样做,因为那样我会构建一个查询:

Gantry::whereHas('sign.lastStatus', function($q){...});

我将按错误状态过滤,以获取至少一个标志有错误的龙门架 - 但我需要在每个标志的最后状态中搜索该错误。

谢谢!

【问题讨论】:

    标签: php mysql laravel orm eloquent


    【解决方案1】:

    我觉得应该是$this->hasMany(Status::class)

    【讨论】:

    • 对不起,我的误解,我认为在这种情况下应该是one-to-many关系
    猜你喜欢
    • 2017-02-28
    • 2015-12-09
    • 1970-01-01
    • 2019-04-25
    • 2022-01-06
    • 2016-12-19
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    相关资源
    最近更新 更多