Laravel Eloquent: nested relationships and data persistence

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 human model, but I have access to the EMPLOYEE_ID. I tried to code, but it doesn't work.

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

      

and

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

      

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

+3


source to share


1 answer


Try this way. When you call person()

it returns the relation instead of the object itself.



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

      

+4


source







All Articles