简体   繁体   中英

Laravel compare two attributes from pivot table

I have a method in my User model, which is supposed to return all expiring qualifications of that user (to be able to warn the employers about it).

Every Qualification has a days_before_warning field, which specifies how many days before it expires the employers should be warned about it.

This is my method:

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

Of course, days_before_warning can not be used that way.

How can I access the days_before_warning attribute to compare it to the valid_until pivot attribute?

I think you need the mysql DATE_SUB function. Something like:

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

You can create a custom pivot model and assign a get accessor for this. It avoids using any more queries than it needs to.

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

As long as you modify your relationship method on you user model to include using():

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

This should allow you to call:

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

To get all of the qualifications where the mutated valid attribute is true. I'm not sure what your relationship method looks like, but I'm assuming you are eager loading qualifications using a with() method. I tested it on one of my pivot models and it seems to be working fine. Let me know if you have any further questions. See some references below:

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

Some SO question I found that could be useful for this (mutators on pivot models): laravel/eloquent mutators/accessors in a pivot table

Edit: Also came across this: https://laracasts.com/discuss/channels/eloquent/how-to-define-an-accessor-for-a-pivot-table-attribute?page=1

it states that you should just be able to provide an accessor on the parent model (user). I have not tested it though, but it may be a simpler option if you do not need the other features that come with a custom pivot model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM