这是 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
,所以连接列在 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);
});
}
}
这是否解决了您的问题?
关于postgresql - Eloquent 中具有不同关系的嵌套 wherehas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31962723/