Laravel Eloquent : Nested relationship and save data

标签 laravel

我有三个模型。

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

EMPLOYEE
id,
person_id

CHILDREN
id,
person_id

我想向人员模型添加一个 child ,但我有权访问 EMPLOYEE_ID。我尝试编写代码,但不起作用。

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

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

但是两者都不起作用。不知道是否可以通过一行代码来完成。

最佳答案

尝试这种方式,当您调用 person() 时,它将返回关系而不是对象本身。

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

关于Laravel Eloquent : Nested relationship and save data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30726213/

相关文章:

Laravel Herd + Wordpress 不写入 debug.log

mysql - 获取用户的 DISTINCT id 并找到其列的 MAX,然后更新、LARAVEL

拉拉维尔 : What is the difference between `locale` and `fallback_locale` ?

php - guzzlehttp 在 Laravel 项目上抛出错误 - strtolower() : Argument #1 ($string) must be of type string, int 给出

php - Laravel Eloquent 的基本选择不起作用

php - 为什么在 Laravel 5.x 中弃用了 Form 和 HTML 助手?

javascript - ajax返回空白数据

php - Laravel 上一个和下一个记录

php - 按实时计算的值(未存储)对元素进行排序

php - 对每个组的用户有限制的预加载