【问题标题】:Laravel - Eloquent filter where Left Join does not existLaravel - 左连接不存在的雄辩过滤器
【发布时间】:2020-06-22 23:34:44
【问题描述】:

我试图弄清楚如何使这个查询工作。这两个表没有直接关系(即 hasOne、hasMany 等)。我希望只从client_vendor_relationship 取回没有collection_opt_in 的记录。由于我没有办法做->whereDoesntHave(),我不确定如何取回这些数据。

client_vendor_relationship

| id | client_id | vendor_id | active |
|----|-----------|-----------|--------|
| 1  | 23484     | 1872      | 1      |
| 2  | 5643      | 345       | 1      |
| 3  | 431       | 4443      | 1      |


collection_opt_in

| id | client_id | vendor_id | year |
|----|-----------|-----------|------|
| 1  | 23484     | 23484     | 2020 |
| 2  | 23484     | 23484     | 2019 |
| 3  | 431       | 4443      | 2019 |

当前查询

$relationships = ClietVendorRelationship::where('active', 1)
->leftJoin('collection_opt_in', function($join){
  $join->on('client_vendor_relationship.client_id', '=', 'collection_opt_in.client_id')
  ->on('client_vendor_relationship.vendor_id', '=', 'collection_opt_in.vendor_id');
})
->where() // Not sure what to put here to ONLY get rows back that the left join didnt find entries for
->groupBy('client_vendor_relationship.id')
->get();

上述查询的最终目标是只从client_vendor_relationship 获取ID 为2 的行。我需要在 Eloquent 中执行此操作。我知道我可以轻松地做一个集合过滤器,但我使用的前端表需要返回一个雄辩的查询。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    为什么要使用左连接?还有其他直接的方法吗?

    你可以使用'whereNotExists':

       $relationships = ClietVendorRelationship::where('active', 1)
                ->whereNotExists(function ( $query){
                $query->select('collection_opt_in.id')->from('collection_opt_in')->
                    whereColumn('collection_opt_in.client_id', '=', 'client_vendor_relationship.client_id')-> 
    whereColumn('collection_opt_in.vendor_id', '=', 'client_vendor_relationship.vendor_id');
                    })
                    ->groupBy('client_vendor_relationship.id')
                    ->get();
    

    我也必须说我不建议在没有聚合的情况下使用 group by

    【讨论】:

    • 完美运行。谢谢!
    猜你喜欢
    • 2018-02-10
    • 2020-03-24
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 2014-07-01
    • 2018-11-18
    • 1970-01-01
    • 2018-06-03
    相关资源
    最近更新 更多