2017-09-24 114 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。