wbail
wbail

Reputation: 566

Laravel query relationship where clause

I need filter by departamento, like where('departamento_id', '=', 1).

Tables:

membro_bancas
id
departamento_id
user_id


trabalhos
id
titulo
orientador_id (references id of membro_bancas)
coorientador_id (references id of membro_bancas)

I have this code:

$trabalho = Trabalho::with('membrobanca.departamento')
    ->with('coorientador')
    ->with('academico')
    ->get();

And returns this:

enter image description here

Upvotes: 1

Views: 6308

Answers (2)

wbail
wbail

Reputation: 566

I got it!

I needed add orWhereHas for coorientador too. The result is this:

Trabalho::whereHas('membrobanca', function($q) use ($departamento_id) {
    $q->where('departamento_id', '=', $departamento_id);
})
->orWhereHas('coorientador', function($q) use ($departamento_id) {
    $q->where('departamento_id', '=', $departamento_id);
})
->with('academico')
->get();

Upvotes: 3

ZeroOne
ZeroOne

Reputation: 9117

Try this eloquent filter using whereas

$trabalho = Trabalho::whereHas('membrobanca',function($query) use ($id){
     $query->where('departamento_id', '=', $id)
})
->with('coorientador')
->with('academico')
->get();

example of filter using with

$trabalho = Trabalho::with(['membrobanca',function($query) use ($id){
     $query->where('departamento_id', '=', $id)
}])
->with('coorientador')
->with('academico')
->get();

Upvotes: 1

Related Questions