【问题标题】:Laravel compare two attributes from pivot tableLaravel 比较数据透视表中的两个属性
【发布时间】:2019-03-30 04:36:08
【问题描述】:

我的User 模型中有一个方法,它应该返回该用户的所有到期资格(以便能够警告employers)。

每个Qualification 都有一个days_before_warning 字段,该字段指定在到期前多少天,应警告employers

这是我的方法:

  return $this->qualifications()
      ->wherePivot('valid_until', '!=', null)
      ->wherePivot('valid_until', '<=', Carbon::today()->subDays('days_before_warning'))
      ->get();

当然,days_before_warning 不能这样使用。

如何访问days_before_warning 属性以将其与valid_until 主元属性进行比较?

【问题讨论】:

    标签: php laravel eloquent laravel-query-builder


    【解决方案1】:

    您可以创建自定义数据透视模型并为此分配 get 访问器。它避免使用比它需要的更多的查询。

    class QualificationsPivot extends Pivot{
        public function getValidAttribute(){
            return $this->attributes['valid_until'] <= $this->atttributes['days_before_warning'] 
        }
    }
    

    只要修改用户模型上的关系方法以包含 using():

    return $this->belongsToMany(Qualifications::class, 'qualifications_pivot_table_name', 'user_id', 'qualifications_id')
            ->using(QualificationsPivot::class)
            ->withPivot(['valid_until', 'days_before_warning']);
    

    这应该允许你调用:

    $this->Qualifications->where('pivot.valid', true);
    

    获取变异的有效属性为真的所有资格。我不确定您的关系方法是什么样的,但我假设您渴望使用 with() 方法加载资格。我在我的一个枢轴模型上对其进行了测试,它似乎工作正常。如果您还有其他问题,请告诉我。请参阅下面的一些参考资料:

    using() 方法: https://medium.com/@codebyjeff/custom-pivot-table-models-or-choosing-the-right-technique-in-laravel-fe435ce4e27e

    我发现一些可能对此有用的 SO 问题(枢轴模型上的突变器): laravel/eloquent mutators/accessors in a pivot table

    编辑:也遇到了这个:https://laracasts.com/discuss/channels/eloquent/how-to-define-an-accessor-for-a-pivot-table-attribute?page=1

    它声明您应该能够在父模型(用户)上提供访问器。虽然我没有对其进行测试,但如果您不需要自定义枢轴模型附带的其他功能,它可能是一个更简单的选择。

    【讨论】:

      【解决方案2】:

      我认为你需要 mysql DATE_SUB 函数。比如:

      return $this->qualifications()
        ->wherePivot('valid_until', '!=', null)
        ->wherePivot('valid_until', '<=', DB::raw('DATE_SUB(NOW(), INTERVAL days_before_warning DAYS')))
        ->get();
      

      【讨论】:

        猜你喜欢
        • 2015-09-26
        • 2018-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-16
        • 1970-01-01
        • 1970-01-01
        • 2018-08-18
        相关资源
        最近更新 更多