2017-09-23 45 views
1

我有表'project','user'和'role_mapping'。我想從項目表中獲取project_owner_id,並推送從user表和role_id中獲取的user_id = 1在role_mapping table.one項目所有者有多個project.so我想限制重複條目。我想在laravel控制器控制器中完成它。獲取並推送新表中的數據

project table 
project_id project name project_owner_id 
1    DEC01 
2    DEC02 
3    DEC01 

user table 
id user_string 
1  DEC03 
2  DEC01 
3  DEC02 

role_mapping table 
user_id role_id 
2  1 
3  1  

$heads = DB::table('project') 
     ->join('users', 'project.project_owner_id', '=', 'users.user_string') 
     ->select('project.project_owner_id','users.id as user_id')->get(); 
     foreach($heads as $head){ 
      print_r($head->project_owner_id); 
      print_r($head->user_id);    
     } 

下面的查詢獲取項目業主ID和user_id.How推在role_mapping表中的值

+0

檢查多在https://laravel.com/docs/5.5/eloquent-relationships#inserting-and-updating很多插入的相關模型 –

+0

你有與用戶表相對應的模型嗎?你能分享嗎? – Rakib

回答

1

像這樣

假設您的型號名稱爲MappingTable

foreach($heads as $head){ 
    $mapTable = new MappingTable(); 
    $mapTable->user_id = $head->user_id; 
    $mapTable->role_id = $head->project_owner_id; 
    $mapTable->save();    
} 

或者你也可以通過$data陣列這樣

$data = array(
    array('user_id'=>$head->user_id, 'role_id'=>), 
    array('user_id'=>$head->user_id, 'role_id'=> $head->project_owner_id), 
    //... 
); 

MappingTable::insert($data); // Eloquent 
DB::table('role_mapping table')->insert($data); // Query Builder 
相關問題