postgresql - Eloquent 中具有不同关系的嵌套 wherehas

标签 postgresql laravel laravel-5 eloquent

这是 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/

相关文章:

laravel - 如何使用另一个有关系的表中的数据(user_id)从用户表中检索用户名

javascript - 如何在larvel5.0中使用带有数组输入的save方法

sql - 将纪元转换为时间戳时获取不正确的日期

postgresql - 带参数和 dblink 的 postgres 函数

laravel - Laravel 中 POST 方法的路由回退?

bash - Artisan 显示插入 "32m"、 "34;4m"和类似的

mysql - Eloquent 模型 : Define on-to-one relationship using flag on child table

laravel-5 - Laravel 5.5 黄昏无法工作

sql - 通过解除 JSON 数组的嵌套在 PostgreSQL 中进行批量更新

Python 2.7 + Django 1.7 + PostgreSQL 9.3 : I'm getting a UnicodeEncodeError when trying to save some text to my database. 给出了什么?