I have two relationship table. I used with using where to filter records as well as i used wherehas using where to filter records. But can’t find the differences between both
I have two relationship table. I used with using where to filter records as well as i used wherehas using where to filter records. But can’t find the differences between both
3
Answers
If you use where(condition)->with(relation) the query will return the records where condition matches and the relation data if any.
Wherase if you use where(condition)->whereHas(relation) the query will return the records where condition matches and where there exists a relation
When you use with() with where() condition, you are applying the condition only on the main table not on the related table, but when you use whereHas() this will apply the condition on the relationship, not on the main table.
e.g
First will fetch the user who has the user id 1,
while second will fetch all the users with posts whose status is published
1). Where()
simple get the data with this
"relation-name"
against thiswhere(condition)
there is no condition apply on the 2nd table (relationship table);
2). Wherehas()
wherehas() apply condition on the 2nd table (relationship table);
My understanding and also have practiced this way in my projects.