Doubts with relationships in Eloquent

Asked

Viewed 641 times

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?

  • I don’t understand! I edit what comes back to me when I do Item::find(2)->users;

  • what returns you if you do: dd(Item::find(1)->usuarios())

  • is edited!!!

  • Is there a problem with the answers? Could you give us a feedback?

2 answers

4

What you should do is say that beyond the items you want the typeUser of the users, and this you do using the method with().

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

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

4


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

There are two ways:

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

OR

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

Browser other questions tagged

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