Filter a query using an attribute in Laravel

Asked

Viewed 856 times

0

I have, briefly, the following structure::

Suppliers: id | cnpj | razao_social | endereco_id
People: id | nome | tipo_pessoa | fornecedor_id
Addressee: id | logradouro | cep

Model - Supplier:

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

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

Model - Pessoa:

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

Model - Address:

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

Vendorcontroller:

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

I want to show a supplier, his address and the people related to it. The query in my controller works, however, I want the consultation to bring only people who have tipo_pessoa = CF or RF

How can I use something like 'WHERE' to do this in consultation?

1 answer

1


Talk brother, come on.

It is possible to do Eager Loading

Information: http://culttt.com/2013/12/30/eager-loading-laravel-4/

That in your case it 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 am passing the Where condition to the relationship, ie only return me the suppliers where the person is type CF or RF.

It is also possible to do directly on the model:

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

Need only call, hugs!

  • I used it on the model and it worked perfectly. Thanks again, @juniorb2ss!

  • 1

    @Buback only that in the model it will impose this rule for ALL relationship. Do not forget to mark the answer as the correct one.

  • Okay, I’m going to test both ways and see what impact I want. Thank you very much.

  • another question: how do I bring city and state that are also in their respective tables?

  • How so? You want to bring the city the supplier belongs together with the state the city belongs to?

  • That, in my model supplier I only refer the Address, as I can do for the address search the city and the state. In the address table has city_id and in the city table has stay_id.

  • Just create a relationship. endereco belonsTo cidade and cidade belongsTo estado. Then just recover with $addressee->city->name; or $addressee->city->state->name;

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.