quick icon indicating copy to clipboard operation
quick copied to clipboard

doesntHave returns incorrect data on to-one relationships when foreign key is null

Open jclausen opened this issue 5 years ago • 1 comments

doesntHave currently creates a WHERE NOT EXISTS sub-select on a to-one relationship that looks like this:

SELECT * 
FROM [myTable] 
WHERE NOT EXISTS (SELECT 1 FROM [myOtherTable] WHERE ([myOtherTable].[id] = [FK_otherTable]))

This means that if FK_otherTable is null, it will return all of those records, in addition to any where the empty does not exist.

The workaround, of course, is to use whereNull( 'FK_otherTable' ) but it seems like doesntHave should be able to handle belongsTo relationships

jclausen avatar Nov 11 '20 21:11 jclausen

I want to make sure I understand here.

If the record from myTable looks like this: { id = 1, FK_otherTable = NULL }, then I would argue that the query is correct — this record does not have a related record. If you also only wanted records that had non-null values for FK_otherTable, that would need to be added to the query.

Did I understand that correctly?

elpete avatar Dec 06 '23 06:12 elpete