通过manyToMany相关的计数模型只有当一个pivot属性为null - Laravel [英] Counting Models related through manyToMany only if a pivot attribute null - Laravel

查看:162
本文介绍了通过manyToMany相关的计数模型只有当一个pivot属性为null - Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在详细说明收集的代码
ManyToMany relation - 如何更新属性在透视表

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

我想要收集活动与任何每周例程相关。数据透视表的贡献 done_at 告诉我什么时候任何活动(任务)完成。

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.

我可以列出, code> - > count()与多个关系中的父模型相关的活动:

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();
}

现在我想要收集一些尚未完成的活动。他们有一个枢轴属性 done_at 设置为 null

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

我希望下面的代码工作。不幸的是它没有。
我得到错误非法操作符。当代替'!='我简单地把'=',代码的工作就像一个梦想,但它给我列出已经完成的活动。

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.

任何提示?

public function activitiesOnlyDone()
{

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






其他提示:
获得额外的数据透视表栏的价值laravel

推荐答案

我相信在这种情况下,您可以将

I believe in this instance, you can replace the

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

与简单的

->whereNull('done_at');

如果另一个 done_at 列你必须做的表

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

->whereNull('activity_routine.done_at');

这是因为Relation类使用Laravel的查询构建器来构建最终的数据库查询。并且在关系类中未定义的关系上调用的任何方法将通过 __ call()方法。

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.

这篇关于通过manyToMany相关的计数模型只有当一个pivot属性为null - Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆