2017-05-05 51 views
0

我想通過Eloquent插入兩個相關的對象,我在其中一個表上獲得了一個Integrity constraint violation error。下面是我想:通過Eloquent在Laravel中插入父母和孩子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(); 

然後保存第二個模型

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

這不會從DB檢索數據在所有,$dataParticipant ID將被自動設置最後一個插入ID