Zed
Zed

Reputation: 5931

one-to-many relationship doesn't work

I am trying to create one-to-many relationship with 2 models, User and Role. So, I would like that one User can only have one role, and the Role can be assigned to more than User. I tried to follow the offical tutorial on https://laravel.com/docs/5.1/eloquent-relationships#one-to-many, and ended up with this:

class User extends Model 
{
    public function role()
    {
        return $this->belongsToMany('App\Admin\Role');
    }
}

class Role extends Model
{

    protected $table = 'roles';

    public function users()
    {
        return $this->hasMany('App\Admin\User');
    }

}

Based on that link, I think the Role is the same thing as the Post, one Role can be assigned to many User. However, this doesn't quite work, here is how I tried to access the role name for a specific User

$role_first = $user->role; // Eloquent\Collection
$role_second = $user->role(); // Eloquent\Relations\BelongsToMany

$role_first->role_title // 'Undefined property: Illuminate\Database\Eloquent\Collection::$role_title'
$role_second->role_title // exception 'ErrorException' with message 'Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$role_title'

What is exactly wrong here?

Upvotes: 1

Views: 157

Answers (4)

Ekalavya
Ekalavya

Reputation: 307

Just make sure the relation

  • A User hasOne Role
  • A Role belongsToMany Users

so, in this condition

class User extends Model 
{
    public function role()
    {
        return $this->hasOne('App\Admin\Role');
    }
}
class Role extends Model
{

    protected $table = 'roles';

    public function users()
    {
        return $this->belongsToMany('App\Admin\User');
    }
}

and must check your user_id foreign constraint be 'unsigned' in your role migration table.

Upvotes: 1

Med
Med

Reputation: 2802

User Model

class User extends Authenticatable{

  public function roles(){
    return $this->belongsTo('App\Admin\Role');
  }
   }

Role Model

    class Role extends Model{

     public function users(){
       return $this->hasMany('App\Admin\User');
     }
      }

The user can have only one role, and the role can be assigned to many users.

Upvotes: 0

Jaylen
Jaylen

Reputation: 40289

This should do it. Please give it a try

class User extends Model 
{
    public function role()
    {
        return $this->hasOne(App\Admin\Role::class);
    }
}

// user belongs to one role
class Role extends Model
{

    protected $table = 'roles';

    public function users()
    {
        return $this->belongsTo(App\Admin\User::class);
    }

}

Upvotes: 0

Mirceac21
Mirceac21

Reputation: 1754

In the User class

public function role()
{
    // not $this->belongsToMany('App\Admin\Role');
    return $this->belongsTo('App\Admin\Role');
}

Because you want a oneToMany not manyToMany relationship.

Upvotes: 2

Related Questions