mohammad-fouladgar/eloquent-builder

Filtering HasManyThrough

joefazee opened this issue · 5 comments

Hello @mohammad-fouladgar ,

Thank you for the fantastic job done so far. I ran into an issue this afternoon trying to filter a has many through relationship.

So I have a project that has applications through another table (roles) and I am trying to filter the applications based on some fields.

Originally I can just do $applications = $project->find(1)->applications()->paginate(10) to fetch the paginated result of all the applications that belongs to that project.

But I want to apply some filtering like by dates, status, etc. I thought I could do

`
$applications = $project->applications()->with(['profile']);

$result = EloquentBuilder::to($applications, request()->all('filters'))->paginate(10);
`

The above code produces an error. See attached screenshot. Maybe I am doing something wrong.
Screenshot 2019-07-27 at 6 14 53 PM

Hi @joefazee ,
thank you for kind words.

Try the following code:

$applications = $project->applications()->getQuery();

$result = EloquentBuilder::to(
                $applications, 
                request()->all('filters')
)->paginate(10);

Can you submit a PR full tested for resolve this issue?

Hello @mohammad-fouladgar, Sorry I had to reopen the issue which I think has nothing to do with this library but from your example, the ->getQuery(); nullified all the relationships.

For example, I can not do

$applications = $project->applications()->with(['media', 'user.profile'])->getQuery();

Do you have any idea why ->getQuery() does not allow fetching of relationships? I have googled already but no good response.

EDITED: changing the query to $project->applications()->newQuery() works with relationship and you can conditionally attach more queries but the getQuery method does not work.

How possible it is for addFilters() to accept this method?

I will close this issue shorty.

Thank you.

Hi @joefazee ,
I'm sorry for the delay, I was very busy in this week.

Please try this way temporarily:

$res = $this->eloquentBuilder
            ->to($project->applications()->select('applications.*')->getQuery())
            ->with(['media'])
            ->get();

Feel free for submit a PR for resolve this issue.

Thank you for responding. I have to use the classic approach, for now, maybe later I can refactor.