Doubts with relationships in Eloquent

13

I am making a belongsToMany to retrieve several Users that are related to a Item .

It returns me in the array all Users correctly, however I need to do hasOne of each User (I created in the model User a method for this), because there is a foreignKey tipo that defines the type of User , and the description is in the other table.

How do I? When I give User::find(1) I can do hasOne , but when I do Item::find(1) and get Users I can not get the Users method that hasOne .

Class User:

class User extends Model {
   //The database table used by the model.
   protected $table = 'usuarios';

   //tipo de usuario
   public function tipoUser(){
       return $this->hasOne('App\TipoUser', 'id', 'tipo');
   }

   public function itens(){
       return $this->belongsToMany('App\Item', 'usuarios_itens', 'id_usuario', 'id_item');
   }
}

Class Item:

class Item extends Model{
   protected $table = 'itens';

   protected $fillable = ['quantidade', 'valor'];

   public function pedido(){
       return $this->belongsTo('App\Pedido', 'id_pedido', 'id');
   }

   //Retorna os usuarios baseado no Model User
   public function usuarios(){
      return $this->belongsToMany('App\User', 'usuarios_itens', 'id_item', 'id_usuario');
   }
}

Return from Item :: find (2) -> Users;

{
   id: 1,
   email: "[email protected]",
   nome: "Fulano de Tal",
   tipo: 1,
   created_at: "2015-05-14 22:10:15",
   updated_at: "2015-05-15 23:03:09",
   pivot: <Illuminate\Database\Eloquent\Relations\Pivot #000000005707178a0000000021afac2b> {
       id_item: 2,
       id_usuario: 1
   }
}

In the index type, I need it to return to me

tipo: {
   id: 1,
   descricao: "Administrador",
   created_at: "0000/00/00 00:00:00",
   updated_at: "0000/00/00 00:00:00"
}
    
asked by anonymous 20.05.2015 / 04:42

2 answers

2

You can use the with method to load relationships. When you convert to JSON , this is the best way to load related data.

There are two ways:

Item::find(2)->usuarios()->with('tipoUser')->get();

OR

Item::with('usuarios.tipoUser')->find(2);
    
25.09.2015 / 16:46
3

What you should do is say that in addition to the items you want the User type of users , and you do this using the with() method.

Item::with('usuarios.tipoUser')
    ->find($id);

There are also alternatives using joins or even Query Builder , but I think this is the simplest one.

    
16.06.2015 / 19:03