gpt4 book ai didi

php - 如何使用 Laravel Eloquent push() 函数?

转载 作者:可可西里 更新时间:2023-11-01 01:01:19 24 4
gpt4 key购买 nike

我正在努力使用 laravel push() 函数

我的代码在这里:

$company = new Company(array('name' => 'Company 1'));
$company->persons[] = new Person(array('name' => 'Company 1 Person 1', 'mobile' => 12345));
$company->persons[] = new Person(array('name' => 'Company 1 Person 2', 'mobile' => 112233));
$company->push();

存储时:公司存储很好,但是对于公司人员,它将company_id存储为0

Larave 文档说:

Sometimes you may wish to save not only a model, but also all of its relationships. To do so, you may use the push method:

$user->push();

怎么了?

最佳答案

这不是教义;)

push 可以做到,但它不会很好也很容易(你可以在下面找到如何做)

下面是您可以改为执行的操作(简单易行的方法):

// still you need already existing Company, so save it first
$company = new Company(array('name' => 'Company 1'));
$company->save();

$company->persons()->createMany(array(
array('name' => 'Company 1 Person 1', 'mobile' => 12345),
array('name' => 'Company 1 Person 2', 'mobile' => 12345)
));

这将保存新的 Person 模型并将它们与 Company 相关联


push 可以完成这项工作,但前提是您使用现有的父模型并且首先关联子模型:

$company = Company::first(); // or any existing

$person = new Person(array('name' => 'Company 1 Person 1', 'mobile' => 12345));
$person->company()->associate($company);

$anotherPerson = new Person(array('name' => 'Company 1 Person 2', 'mobile' => 12345));
$anotherPerson->company()->associate($company);

$company->persons[] = $person;
$company->persons[] = $anotherPerson
$company->push();

显然这是更多的工作,这绝对不是我建议的方式。

关于php - 如何使用 Laravel Eloquent push() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24913816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com