dakine
dakine

Reputation: 699

Laravel Eloquent: Nested relationship and save data

I have three models.

PERSON (hasOne(EMPLOYEE), hasMany(CHILDREN))
id,
name

EMPLOYEE
id,
person_id

CHILDREN
id,
person_id

I want to add a child to person model but i have access to EMPLOYEE_ID. I tried to code but it doesn't work.

$employee->person()->children()->save($child);

and

$employee->person()->children()->associate($child);

But both doesn't work. I don't know if this can be accomplished by just one line of code.

Upvotes: 5

Views: 3305

Answers (1)

chanafdo
chanafdo

Reputation: 5124

Try this way, When you are calling person() it will return the relation instead of the object itself.

$employee->person->children()->save($child);

Upvotes: 6

Related Questions