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:
tenants table
Id | user_id | property_id |
---|---|---|
1 | 1 | 1 |
2 | 2 | 1 |
3 | 3 | 1 |
rent_paids
Id | user_id | property_id | amount_paid |
---|---|---|---|
1 | 1 | 1 | 3000 |
I want to be able to return the users in the tenants table and not in the rent_paids table. In this case, users 2 and 3
. But the above code returns an empty array.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You’re missing the where clause to tie it back to the original table.
$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();
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0