仅当pivot属性为null时才计算通过manyToMany相关的模型 - Laravel

时间:2016-04-26 05:38:12

标签: laravel eloquent pivot-table laravel-5.2 relation

我正在详细说明这里获得的代码 ManyToMany relation - how update attribute in pivot table

我想要的是什么:

我想获得与每周Activities相关的Routine集合。数据透视表的属性done_at告诉我任何活动(任务)何时完成。

我可以在manyToMany关系中列出与之后->count()与父模型相关的活动:

public function activities()
{

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

现在我想获得一些尚未完成的活动。他们将数据透视属性done_at设置为null

我的尝试:

我希望以下代码有效。不幸的是,它没有。 我收到错误Illegal operator。当我简单'!='代替'='时,代码就像梦一样,但它给了我已经完成的活动列表。

任何提示?

public function activitiesOnlyDone()
{

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

其他提示: getting the value of an extra pivot table column laravel

1 个答案:

答案 0 :(得分:1)

我相信在这个例子中,你可以替换

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

用简单的

->whereNull('done_at');

如果其他表上有done_at列,则必须执行

->whereNull('activity_routine.done_at');

这是有效的,因为Relation类使用Laravel的查询构建器来构造最终的数据库查询。并且任何调用未在Relation类中定义的关系的方法都将通过__call()方法传递给查询构建器(Illuminate \ Database \ Query \ Builder)。