Postgresql 在雄辩中有不同关系的嵌套

Postgresql 在雄辩中有不同关系的嵌套,postgresql,laravel,laravel-5,eloquent,Postgresql,Laravel,Laravel 5,Eloquent,以下是Laravel 5应用程序中雄辩类之间的一些关系: B属于A B有一个C 表是使用正确的外键生成的。 以下是a的作用域方法: public function scopeMyScope(Builder $query) { return $query->whereHas('B.C', function($q) { $q->whereRaw("1=1"); }); } 如果调用A::myScope()->get(),将导致SQL错误,因为lar

以下是Laravel 5应用程序中雄辩类之间的一些关系:

  • B
    属于
    A
  • B
    有一个
    C
表是使用正确的外键生成的。 以下是
a
的作用域方法:

public function scopeMyScope(Builder $query) 
{
    return $query->whereHas('B.C', function($q) {
        $q->whereRaw("1=1");
    });
}
如果调用
A::myScope()->get()
,将导致SQL错误,因为laravel生成了以下查询:

select * from "a" where (select count(*) from "b" where "a"."a.b_id" = "b"."id" and (select count(*) from "c" where "c"."b_id" = "b"."id" and 1=1) >=1 ) >= 1
错误是:

Illuminate\Database\QueryException with message 'SQLSTATE[42703]: Undefined column: 7 ERROR:  column c.b_id does not exist

因此,生成的查询是错误的,因为没有
c.b_id
列(因为
b有一个c
,所以join列位于
c
)。我是做错了什么,还是laravel的query builder中有一个bug?

据我所知,你需要做一个嵌套的whereHas,所以:

public function scopeMyScope(Builder $query)
{
    // b is the name of the relationship...
    return $query->whereHas('b', function($q)
    {
         // c is the name of the relationship...
         $q->whereHas('c', function()
         {
             $q->where(1, 1);
         });
    }
}
这能解决你的问题吗