简体   繁体   English

Laravel表关系问题

[英]Laravel tables relations issue

I am new with Laravel, I have two tables users and roles related via pivot table role_user but I deleted pivot table and put foreign key id_role in table user but I need also to change this code but I find some problems. 我是Laravel的新手,我有两个表用户和通过数据透视表role_user相关的角色,但是我删除了数据透视表并将外键id_role放在表user但是我还需要更改此代码,但发现一些问题。

@if(!empty($user->roles))
    @foreach($user->roles as $v)
        <label class="label label-success">{{ $v->display_name }}</label>
    @endforeach
@endif

Thanks for help. 感谢帮助。

User model : 用户模型:

class User extends Model {

  public function roles()
  {
    return $this->hasMany(Roles::class);
  }

Role migration file : 角色迁移文件:

public function up()
{
  Schema::create('roles', function(Blueprint $table)
  {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')
      ->references('id')->on('todolists')
      ->onDelete('cascade');
    $table->string('name');
    $table->timestamps();
  });
}

Role model : 榜样 :

class Role extends Model {

  public function user()
  {
    return $this->belongsTo(User::class);
  }

}

now you can do this : 现在您可以执行以下操作:

@if(!empty($user->roles))
    @foreach($user->roles as $v)
        <label class="label label-success">{{ $v->display_name }}</label>
    @endforeach
@endif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM