2017-05-05 14 views
0

Eloquent을 통해 두 개의 관련 개체를 삽입하려고하는데 테이블 중 하나에 Integrity constraint violation error이 표시됩니다.Laravel의 Eloquent를 통해 한 번에 부모와 자식 삽입 5.4

관계의 표현 : 여기에 내가 노력하고 무엇을 다음

class DataParticipant extends Model 
{ 
    public function data_config() 
    { 
     return $this->hasOne('App\Models\DataConfig'); 
    } 
} 

class DataConfig extends Model 
{ 
    public function data_participant() 
    { 
     return $this->belongsTo('App\Models\DataParticipant'); 
    } 
} 

을, 나는 시도하고 다음

$dataParticipant = new DataParticipant(); 

$dataParticipant->ip = // ip 
$dataParticipant->code = // code 
$dataParticipant->study_name = // study 


// Prepare the config child. 

$dataConfig = new DataConfig(); 
$dataConfig->config = // config via json_encode 


// Store the child associated to the parent. 

$dataParticipant->data_config()->save($dataConfig); 

오류가에 속하는 data_participant_id 열,에 DataConfig 모델. 내 생각 엔 두 사람을 연결할 수있는 id이 없다는 것입니다. 난 당신을 물어보고 싶은 :

  • 어떻게 먼저 다음 DataParticipant을 저장 데이터베이스에서 검색 한 후 결과 idDataConfig를 저장하지 않고이 작업을 수행 할 수 있습니까?
+1

'$ dataParticipant'를 (를) 저장하려고 했습니까? $ dataConfig를 생성하기 전에'$ dataParticipant-> save()'를 실행하십시오. 문제가 지속되면 최종 행에서 사용하기 전에 $ dataParticipant를 새로 가져 오십시오. –

답변

0

먼저

$dataParticipant->save(); 

다음이 전혀 DB에서 데이터를 검색하지 않습니다

$dataParticipant->data_config()->save($dataConfig); 

두 번째 모델을 저장하고 $dataParticipant ID가 자동으로 설정됩니다 첫 번째 모델을 저장 마지막 삽입 ID