【问题标题】:Laravel wherenotexists returning nullLaravel wherenotexists 返回 null
【发布时间】:2021-04-20 12:00:36
【问题描述】:

我有以下代码

 $not_paid = Tenant::where('property_id', $property_id)
            ->whereNotExists(function ($query) use ($property_id) {
                $query->select('user_id')
                ->from('rent_paids'); 
            })
            ->get();

应该是获取某个属性的所有租户,在rent_paids表中查找,返回不在rent_paids表中的用户,如下:

租户表

Id user_id property_id
1 1 1
2 2 1
3 3 1

租金支付

Id user_id property_id amount_paid
1 1 1 3000

我希望能够返回租户表中的用户,而不是rent_paids 表中的用户。在这种情况下,用户2 and 3。但是上面的代码返回的是一个空数组。

【问题讨论】:

  • ->whereNotExists() 不接受 2 个值/参数吗?哪里不存在于什么?
  • @DimitriMostrey 不,closure is correct

标签: php mysql laravel eloquent


【解决方案1】:

您缺少将其绑定回原始表的 where 子句。

$not_paid = Tenant::where('property_id', $property_id)
        ->whereNotExists(function ($query) use ($property_id) {
            $query->select('user_id')
            ->from('rent_paids')
            ->whereColumn('tenants.user_id', '=', 'rent_paids.user_id'); 
        })
        ->get();

【讨论】:

  • 我认为这需要whereColumn,尽管看起来join 可能比whereNotExists 更合适。此外,它可能需要与$property_id 联系起来,但从这个问题来看,它是如何联系起来的还不清楚。
  • 你说得对,它确实需要是 whereColumn。我正在关注laravel.com/docs/8.x/queries#where-exists-clauses 上的示例
猜你喜欢
  • 2016-11-29
  • 2017-08-05
  • 2019-04-17
  • 2023-03-28
  • 2022-06-12
  • 2014-07-30
  • 2014-08-21
  • 2016-11-20
  • 2016-11-08
相关资源
最近更新 更多