Filter a query using an attribute in Laravel

0

I have, in short, the following structure:

Suppliers : id | cnpj | razao_social | endereco_id
People : id | nome | tipo_pessoa | fornecedor_id

Model - Supplier:

public function endereco() {
    return $this->hasOne('App\Endereco', 'id', 'endereco_id');
}

public function pessoa() {
    return $this->hasMany('App\Pessoa');
}

Model - Person:

public function fornecedor() {
    return $this->belongsTo('App\Fornecedor', 'id', 'fornecedor_id');
}

Model - Address:

public function fornecedor() {
    return $this->belongsTo('App\Fornecedor');
}

SupplierController:

public function show($id) {
    $fornecedor = Fornecedor::find($id)->with('endereco', 'pessoa')->get();
    return view('admin.fornecedores.visualizar', compact('fornecedor'));
}

I want to show a vendor, its address, and people related to it. The query in my id | logradouro | cep works, however, I want the query to bring only people who have controller = tipo_pessoa or CF

How can I use something like ' RF ' to do this in the query?

    
asked by anonymous 15.09.2015 / 17:54

1 answer

1

Speak brother, come on.

You can do Eager Loading

Information: link

That in your case would be something more or less give:

$Fornecedores = Fornecedores::with(array('fornecedores.pessoa' => function($query)
{
  $query->WhereIn('tipo_pessoa',['CF', 'RF']);
}))->get();

In this example I'm passing the where condition to the relationship, that is, it only returns me the suppliers where the person is CF or RF type.

You can also do it directly in the model:

public function pessoa() {
   return $this->hasMany('App\Pessoa')->WhereIn('tipo_pessoa',['CF','RF']);
}

Just need to call, hugs!

    
15.09.2015 / 18:09