简体   繁体   中英

Laravel - how to make a search filter with like anything in relationship columns

I'm trying to make a query where returns me the results, based on a request word, but I have to filter with the relationship columns as well. Example:

Payment::byUnity($unityId)
            ->with(['contract:id,nome,sigla'])
            ->latest('id')
            ->where('id', 'LIKE', '%' . $request->input('search') . '%')
            ->orWhere('name', 'LIKE', '%' . $request->input('search') . '%')
            ->orWhere('contract.name', 'LIKE', '%' . $request->input('search') . '%')
            ->orWhere('contract.description', 'LIKE', '%' . $request->input('search') . '%')
            ->paginate(15)

How can I filter the "contract.name" on the query? Because the way of the example returns me error. Thanks in advance!

You can do

Payment::byUnity($unityId)
            ->with(['contract:id,nome,sigla'])
            ->latest('id')
            ->where('id', 'LIKE', '%' . $request->input('search') . '%')
            ->orWhere('name', 'LIKE', '%' . $request->input('search') . '%')
            ->orWhereHas('contract', function($query) use ($request) {
                return $query->where('name', 'LIKE', '%' . $request->input('search') . '%')
                ->orWhere('description', 'LIKE', '%' . $request->input('search') . '%');
            }
            ->paginate(15)

NOTE: You must have proper relationships set up for this query to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM