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"
}