0

I am elaborating code acquired here ManyToMany relation - how update attribute in pivot table

what I want:

I want to get a collection of Activities related to any weekly Routine. The pivot table's atribute done_at tells me when any activity (task) was completed.

I can list and later ->count() activities related to parent model in manyToMany relation:

public function activities()
{

    return $this->belongsToMany('App\Models\Activity', 'activity_routine', 'routine_id', 'activity_id')->withPivot('done_at')->withTimestamps();
}

Now I want to get a collection of activities, which are not yet done. They have a pivot attribute done_at set to null.

my attempt:

I wish the below code worked. Unfortunately it doesn't. I get error Illegal operator. When in stead of '!=' I put simply '=', the code works like a dream, but it gives me list of Activities already done.

Any hints?

public function activitiesOnlyDone()
{

    return $this->belongsToMany('App\Models\Activity')->withPivot('done_at')->wherePivot('done_at','!=',null);
}

Additional hints: getting the value of an extra pivot table column laravel

Community
  • 1
  • 1
Peter
  • 2,634
  • 7
  • 32
  • 46

1 Answers1

1

I believe in this instance, you can replace the

->wherePivot('done_at','!=',null);

with a simple

->whereNull('done_at');

If there are done_at columns on the other tables you will have to do

->whereNull('activity_routine.done_at');

This works because the Relation class uses Laravel's query builder to construct the final database query. And any methods called on a relation that are not defined in the Relation class will be passed to the query builder (Illuminate\Database\Query\Builder) via a __call() method.

programmerKev
  • 399
  • 1
  • 3
  • 7
  • much to my sorprise it works. Thank you. I have also submitted a bug report to Laravel/Framework, as the `Illegal operator` error is sth that needs fixing. Thank you! – Peter Apr 27 '16 at 01:23