Laravel - List with relation of tables (state / city = person)

1

I have the following tables:

contacts = > id - name - state - city

states = > id - status - acronym

cities = > id - city - state_id

And the following templates:

State.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Estado extends Model{
    protected $table = 'estados';
    public $timestamps = false;

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

Contact.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Contato extends Model{
    protected $table = 'contatos';
    public $timestamps = false;

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

And to list:

$request = Contato::orderBy($column, $sort)->paginate($paginator);

And how do I make the state name (the same goes for the neighborhood) instead of the state id

    
asked by anonymous 03.05.2016 / 01:13

1 answer

1

Well, come on. First let's ask some questions as to their logic and if possible some corrections.

Contato hasMany Estados

A free translation is saying that: Contact contains several States.

Is this correct?

It would not be more concrete: Contact has a city or Contact belongs to a state, because in the matter of the integrity of your application it is not possible to exist a contact without informing the state.

So it would be hasOne or belongsTo relationship

Now let's go to the code.

Each contact you should pull eloquent your relationships, that is, if the contact comes with Carlos Eduardo you should pull the status automatically.

To do this there are two ways in Eloquent.

First

When requesting the contact list you call the relationship

$request = Contato::orderBy($column, $sort)
           ->with('estados', 'bairro') 
           ->paginate($paginator);

This method has a name of Eager Loading Multiple Relationships . You can check the documentation.

What does it do? He says to the eloquent: Dude, with every contact you return to me, do you seek estado and get bairro also from contact, beauty?

Second

This method will define in the model that every query that it undergoes it should call the relationship automatically. This is different from the ONE method, which you define when you want to call the relationship. This method will be in ALL queries.

To use this method simply create a propriedade in the contact model

public $with = ['estado'];

After doing some of these methods to retrieve the state name:

$request = Contato::orderBy($column, $sort)
           ->with('estados', 'bairro') 
           ->paginate($paginator);
foreach(...);
 {{ $contato->bairro->sigla }}
endforeach;

I hope I have helped.

    
03.05.2016 / 15:10