简体   繁体   English

Laravel wherenotexists 返回 null

[英]Laravel wherenotexists returning null

I have the following piece of code我有以下一段代码

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

which is supposed to get all the tenants in a certain property, look them up in the rent_paids table and return the users who are not in the rent_paids table, as follows:这应该是获取某个属性中的所有租户,在rent_paids表中查找它们并返回不在rent_paids表中的用户,如下所示:

tenants table租户表

Id ID user_id用户身份 property_id property_id
1 1 1 1 1 1
2 2 2 2 1 1
3 3 3 3 1 1

rent_paids租金支付

Id ID user_id用户身份 property_id property_id amount_paid支付的金额
1 1 1 1 1 1 3000 3000

I want to be able to return the users in the tenants table and not in the rent_paids table.我希望能够返回租户表中的用户,而不是rent_paids 表中的用户。 In this case, users 2 and 3 .在这种情况下,用户2 and 3 But the above code returns an empty array.但是上面的代码返回一个空数组。

You're missing the where clause to tie it back to the original table.您缺少将其绑定回原始表的 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM