2017-09-24 56 views
0

我有表'角色'与字段user_id和role_id.I已经从另一个查询154,516从for循环获取新值。我想检查154是在角色表user_id如果不退出插入新字段或存在更新字段。在我的情况下,更新user_id'154'的role_id并插入'516'的新行。检查数据库,并插入数据不存在

role //table 
user_id role_id 
210  1 
125  2 
310  1 
154  1 


foreach($heads as $head){ 
      $first_count=$first_count+1; 
      $roleMappingObject = new role_mapping(); 
      $roleMappingObject->user_id = $head->user_id; 
      $roleMappingObject->role_id = 1; 
      $roleMappingObject->save(); //this will insert the new row for both 154 and 516 but I want to update '154' 
     } 

回答

0

设置一个许多人

用户模型用户和角色之间有许多关系

public function roles() 
{ 
    return $this->belongsToMany(Role::class, 'role_user'); 
} 

角色模型

public function users() 
{ 
    return $this->belongsToMany(Role::class, 'role_user'); 
} 

然后

$user->roles()->attach($roleId)); 
1

在你的情况下,它看起来像你的ROLE_ID是不是外键,如果是这样的话,你可以只用雄辩的功能firstOrCreate/ firstOrNew

firstOrCreate将例如搜索与给定的数据并返回该实例或者将保存该实例。

firstOrNew将找到并返回或创建实例,但不会将其保存在数据库中,因为您必须通过调用save()方法来执行此操作。

但是如果你的ROLE_ID是其他表的外键即密钥ID应该比你更喜欢它在laravel的文档中定义的方式为many to many relationship更改作用ROLE_USER和创建用户和角色表之间的关系。这样你就可以使用方法attach/detach。

相关问题