Problems with relationship Many to many

4

I have two many-to-many relationships, a users table and other roles

And I have a user with 3 loaded roles in the database, but when I search, it only brings me 1 role.

class RoleModel extends BaseModel {

protected $table = 'role';
protected $fillable = ['role'];
protected $dates = ['deleted_at'];

public function usuarios() {
    return $this->belongsToMany('Moltareas\Usuario\UsuarioModel', 'role_x_usuario',  'idUsuario','idRole')
                    ->withTimestamps();
}
}

class UsuarioModel extends Authenticatable {

use Notifiable;

protected $table = 'usuario';
protected $fillable = [ 'nombre', 'apellido', 'email', 'password', 'idRole'];
protected $hidden = [ 'password', 'remember_token'];
protected $dates = ['deleted_at'];

public function roles() {
    return $this->belongsToMany('Moltareas\Role\RoleModel', 'role_x_usuario', 'idRole', 'idUsuario')
                    ->withTimestamps();
}
}

And when I bring the user roles I do:

introducir el código aquí

$user = Moltareas\Usuario\UsuarioModel::get();

foreach ($user->roles as $role) {
    var_dump($role);
}

And this only shows me that the user only has 1 role, when in fact he has 3 charged.

If I make a dd ($ role) within the foreach, it shows me this

#attributes: array:5 [▼
"id" => 1
"role" => "ADMINISTRADOR"
"deleted_at" => null
"created_at" => "2016-10-07 09:57:27"
"updated_at" => "2016-10-07 09:57:27"
]
    
asked by Juan Pablo 10.10.2016 в 01:28
source

2 answers

1

Try to make this query and verify that it gives you the results.

SELECT * FROM role_x_usuario WHERE idUsuario = [ID DEL USUARIO]

I think the problem is that you have inverted the fields

class UsuarioModel extends Authenticatable {

    use Notifiable;

    protected $table = 'usuario';
    protected $fillable = [ 'nombre', 'apellido', 'email', 'password', 'idRole'];
    protected $hidden = [ 'password', 'remember_token'];
    protected $dates = ['deleted_at'];

    public function roles() {
    // Acá es donde esta invertido los campos
        return $this->belongsToMany('Moltareas\Role\RoleModel', 'role_x_usuario', 'idUsuario', 'idRole')
                        ->withTimestamps();
    }
}

You can see a very similar example in the laravel documentation

link

    
answered by 05.12.2018 в 00:47
0

Assuming everything is loaded correctly, it seems to me that the problem must be in how you show

$users = Moltareas\Usuario\UsuarioModel::orderBy('id','ASC')->get();
$users->each(function($users){
        $users->roles;
    })
dd($users);

In this each adds to each user the roles with which it is related

    
answered by 10.10.2016 в 02:04