如何在hasMany关系中更改laravel模型?

时间:2019-02-22 13:48:00

标签: php laravel laravel-5

我有一个模型“ Contact”,其中有许多“ Address”。 使用新地址保存联系人时

...
//$contact = some instance of Contact
$contact->addresses()->save(new Address(['street' => '4811 Example Dr.']));

dd($contact->getChanges()); // returns null
// dd($contact->addresses()->getChanges()); // method not available   
// dd($contact->addresses->getChanges()); // method not available

如何查看保存调用后实际进行的更改?

4 个答案:

答案 0 :(得分:1)

$contact->getChanges()返回null,因为getChanges()试图查看通讯录中是否有任何更改,因此没有。

$contact->addresses()->getChanges()也不起作用,因为$contact->addresses()不返回地址模式的实例。

您可以使用简单的检查save响应进行验证,因为它返回布尔值。

$addressSavedSucccessfully = $contact->addresses()->save(new Address(['street' => '4811 Example Dr.']));

if ($addressSavedSucccessfully) {
    dd('address was saved correctly');
} else {
    dd('something went wrong');
}

我希望能帮上忙。

答案 1 :(得分:0)

下面的行返回bolean。您可以检查其返回值。

$value = $contact->addresses()->save(new Address(['street' => '4811 Example Dr.']));


if($value){
   //it is saved
}else{
  //it is not saved    
}

答案 2 :(得分:0)

*已编辑 试试这个

if (!$contact) {
   $changes = $contact->getChanges();
}

答案 3 :(得分:0)

尝试以下操作。对我有用

$this->loadMissing('address');
$address = $this->address;
$address->fill($addressFieldValue);
$address->save();
address->getChanges();