问题
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
回答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.
来源:https://stackoverflow.com/questions/36856090/counting-models-related-through-manytomany-only-if-a-pivot-attribute-null-lara