问题描述
我将关系存储在变量中:
$relation = $model->{$relationConfig['relation']}();
然后我确保其确实具有HasMany关系:
dd($relation);
我看到了这个picture。然后,我像这样使用它:
$relation->associate($newModel);
然后发生此错误:
Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::associate()
我在这里怎么了?
解决方法
$newModel = new Child([
'column' => 'value',])
$relation = Parent::create([
'column' => 'value'
]);
$newModel->belongsToRelation()->associate($relation);
$newModel->save();
//or
$relation = Parent::find(1)->hasMany()->create([
'column' => 'value'
]);