I can not make search work with eloquent and relationship !!! Laravel 5.5 and mysql

1

I am doing a search by taking a word part and playing in a search type LIKE for fields fields. I use Eloquent and relationships, but it does not bring the data.

{
    $pesquisa   = $dataForm['pesquisa'];

    $atestados = Atestado::with([
        'colaborador' => function ($query) use ($pesquisa) {
              $query->where('colaboradors.matricula', 'LIKE', "%{$pesquisa}%")
                    ->orWhere('colaboradors.nome', 'LIKE', "%{$pesquisa}%");
        },
        'cid' => function ($query) use ($pesquisa) {
              $query->orWhere('cids.codigo', 'LIKE', "%{$pesquisa}%");
        },                    
        'situacao' => function ($query) use ($pesquisa) {
              $query->orWhere('situacaos.descricao', 'LIKE', "%{$pesquisa}%");
        },                    
     ])
     ->orderBy('data_afastamento', 'desc')
     ->get();
}
    
asked by anonymous 19.12.2018 / 12:07

1 answer

1

Use whereHas to check the relationship data and with with load the relationship data between entities , for example:

$pesquisa = $dataForm['pesquisa'];
$atestados = Atestado::with(['colaborador','cid','situacao'])
        ->whereHas('colaborador', function ($query) use ($pesquisa)
        { 
            $query->where('matricula', 'like', "%{$pesquisa}%"); 
        })
        ->whereHas('cid' => function ($query) use ($pesquisa) 
        {
            $query->where('cids.codigo', 'LIKE', "%{$pesquisa}%");
        })
        ->whereHas('situacao' => function ($query) use ($pesquisa) 
        {
            $query->where('situacaos.descricao', 'LIKE', "%{$pesquisa}%");
        })
        ->orderBy('data_afastamento', 'desc')
        ->get();

20.12.2018 / 16:07