如何使用save()方法在Eloquent中创建和更新?

时间:2019-11-24 06:38:22

标签: laravel eloquent orm

我用数组形式的对象:

   M  W  HR_High  HR_Low  T_No  T_Yes
0  2  8        0       1     1      0

我正试图通过laravel雄辩的[{"id":"2","passport_number":"AB-2019-11-24-0200","place_issue":"Yuan","date_issue":"2018-10-10","date_expiry":"2018-10-10"}] 方法保存它,如下所示:

save()

我想知道为什么会出现此错误:

private function save_person_passport($object, $person_id, \App\Passport $passport){
    if($object->id > 0){
        $passport->id = $object->id;
    }
    $passport->person_id = $person_id;
    $passport->passport_number = $object->passport_number;
    $passport->place_issue = $object->place_issue;
    $passport->date_issue = $object->date_issue;
    $passport->date_expiry = $object->date_expiry;

    $passport->save(); 
}

save()方法是否用于创建更新

2 个答案:

答案 0 :(得分:1)

您正在创建\App\Passport的新实例,因此它将保存未更新的记录。如果$object->id > 0

,您可以做一件事找到ID

将您的代码替换为下面提到的相同代码,

if($object->id > 0){
    $passport = \App\Passport::find($object->id);
    $passport->id = $object->id;
}
$passport->person_id = $person_id;
$passport->passport_number = $object->passport_number;
$passport->place_issue = $object->place_issue;
$passport->date_issue = $object->date_issue;
$passport->date_expiry = $object->date_expiry;

$passport->save(); 

现在,如果$object->id > 0,它将找到Passport的集合。并更新主键为2

的记录

答案 1 :(得分:0)

尝试一下:

private function save_person_passport($object, $person_id, \App\Passport $passport){
if($object->id > 0){
    $passport = \App\Passport::find($object->id);
      if(!empty($passport){
        $passport->person_id = $person_id;
        $passport->passport_number = $object->passport_number;
        $passport->place_issue = $object->place_issue;
        $passport->date_issue = $object->date_issue;
        $passport->date_expiry = $object->date_expiry;
        $passport->save(); 
      }
    } 
 }