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
然後從數據庫中檢索,然後存儲在導致id
的DataConfig
?
您是否嘗試保存'$ dataParticipant'?在創建$ dataConfig之前請'$ dataParticipant-> save()',如果問題仍然存在,那麼在使用最後一行之前嘗試獲取新的$ dataParticipant。 –