13
Guys I’m making a belongsToMany
to recover several Users
that are related to a Item
.
It returns me in the all array Users
correctly, but I need to make a hasOne
of each User
(created on the model User
a method for this), because there is a foreignKey tipo
defining the type of User
, and the description is on the other table.
How do I do it? When I give User::find(1)
can do the hasOne
, but when I do Item::find(1)
and take the Users
I can’t get the model method Users
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');
}
}
Item Return::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 Indian type, I need you to call me back
tipo: {
id: 1,
descricao: "Administrador",
created_at: "0000/00/00 00:00:00",
updated_at: "0000/00/00 00:00:00"
}
In doing
Item::find(1)->users()
you are iterating (loop) between users?– gmsantos
I don’t understand! I edit what comes back to me when I do Item::find(2)->users;
– Eric123
what returns you if you do:
dd(Item::find(1)->usuarios())
– gmsantos
is edited!!!
– Eric123
Is there a problem with the answers? Could you give us a feedback?
– Wallace Maxters