Counting Models related through manyToMany only if a pivot attribute null - Laravel

那年仲夏 提交于 2020-01-17 05:13:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!