Anyone have an idea?
Query filter on Polymorphic model?
Hi all,
I'm trying to paginate polymorphic Contacts (Business or Person).
The problem is, I can't find a way to add a query filter on the Person model.
I want to get all Contacts, be it a Business or Person, but a Person CANNOT belong to a Business. (for this result set)
My goal is to have an overview of all Contacts, and paginate them.
But I need to exclude the People that belong to a Business.
So, in short: How do I put a filter on my Person model, through the polymorphic Contact model?
I could just fetch 100 Contacts, and use a collection filter to exclude the People that I don't need.
That works. But the query still fetches those unwanted People.
Plus, I can't work properly with pagination, because I won't have 100 results anymore, but maybe 60.
If I would do that, I have no estimate of how many results I would get, and therefor can't paginate them.
I would like to do something like this:
Contacts::filter('people.business_id', '=', null)
->orderBy('created_at', 'DESC')
->skip(0)->take(100)
->get();
And get the following:
1 | Business X
2 | Business Y
4 | Jane Doe (business_id = null)
Tables:
Contacts
--------------------------------------------------
id | contactable_id | contactable_type
--------------------------------------------------
1 | 1 | App\Business
2 | 2 | App\Business
3 | 1 | App\Person
4 | 2 | App\Person
Businesses
----------------------
id | name
----------------------
1 | Business X
2 | Business Y
People
---------------------------------------------------------
id | business_id | first_name | last_name
---------------------------------------------------------
1 | 1 | John | Doe
2 | NULL | Jane | Doe
Happy holidays to all of you!
Please or to participate in this conversation.