1

I am using Laravel 5.7 version.

I would like to use multiple eager loading with where clauses.

I have laravel simplified.

$query = Employee::with(['User','Company','Client'])
                  ->select(*)->whereRaw("(User.id <> 0 and Company.name LIKE %A%) OR Client.id <> 0)")

I am using eager loading to avoid JOIN statement.

But the problem is the error message says User.id is unknown column in where clause.

I believe the other two would be unknown columns as well.

Any ideas would be appreciated.

1 Answer 1

1

It looks a bit uggly, but you can use a closure:

$query = Employee::with('User', function ($inner) {
    $inner->where('id', '!=', 0);
})->with(['Company', 'Client'])
->where(function (Builder $sub) use($companyName) {
    $sub->where('Company.name', 'like', $companyName)
        ->orWhere('Client.id', '!=', 0);
})->get();

This will retrieve:

employees where (user.id != 0 AND (company.name LIKE :companyName OR client.id != 0))

In order to modify the order of those constraints you'll need to move the closure and constraints according to your requirements, but for what I understood this should do it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.