问题:在 Eloquent 中以不同关系嵌套 wherehas

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

  • 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 hasOne C,所以join列在C中)。我做错了什么还是 laravel 的查询生成器中的错误?

解答

据我所知,你需要做一个嵌套的 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);
         });
    }
}

这能解决你的问题吗?

Logo

PostgreSQL社区为您提供最前沿的新闻资讯和知识内容

更多推荐