Laravel HasMany has no attach or associate method?

Viewed 374

I store relationship in variable:

$relation = $model->{$relationConfig['relation']}();

then i make sure that its indeed HasMany relationship:

dd($relation);

And i see this picture. Then, i am using it like so:

$relation->associate($newModel);

And then this error happens:

Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::associate()

Whats wrong am i doing here?

1 Answers
$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'
]);
Related