When I retrieve data directly from the model using the following approach:
Contact::where('company_id', auth()->user()->company_id)->get()
The query looks like this:
select * from "contacts" where "company_id" = 'xxx'
But when I retrieve data through direct relations like this:
auth()->user()->company->contacts
The query looks like this and takes longer:
select * from "contacts" where "contacts"."company_id" = 'xxx' and "contacts"."company_id" is not null
It adds the additional;
and "contacts"."company_id" is not null
part, which affects performance negatively. What should I do to prevent this? Querying directly from models without using relations anywhere also doesn't seem very logical and clean.
Note: company_id is indexed.
$company = new Company;
The Company model hasn't been saved yet, so there is no primary key yet, it exists only as a PHP object, but since relationships will generate and execute SQL, the $contacts variable below will be filled with values where company_id is null. To prevent this, IS NOT NULL has been added to the query.
$contacts = $company->contacts;