使用雄辩的方式从一个表单创建多个模型中的记录

时间:2016-05-09 00:11:41

标签: mysql laravel eloquent

我有一个表单,用于捕获用户详细信息并希望保存为两个单独的模型:联系人 contract_addresses

以下是我在控制器方法中$request->all()的输出:

{
  "first_name": "Joe",
  "last_name": "Jackson",
  "nickname": "JJ",
  "salutation": "Mr",
  "contact_address": {
    "phone_mobile": "123456789",
    "email": "jj@jackson.com",
    "address_1": "123 Office",
    "postcode": "2334",
    "address_2": "456 Lane",
    "province": "New Portia",
    "city": "Okalaville",
    "country": "Golubia"
  }
}

我在模型中建立了适当的关系,如下所示:

联系模式:

public function address()
{
    return $this->hasOne('App\Contact_address');
}

Contact_Address模型:

public function contact()
{
    return $this->belongsTo('App\Contact');
}

控制器方法: 以下是我设置控制器方法的方法:

public function store(Request $request)
{
    $contact = new Contact($request->except("contact_address"));
    $contact_address = new Contact_address($request->contact_address);
    $contact->setRelation('address', $contact_address);
    $contact->push();
    return back();
}

使用push()的错误:上面的push()会抛出2个SQL异常:

Connection.php第408行中的1/2 PDOException:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`myappdb`.`contact_addresses`, CONSTRAINT `contact_addresses_contact_id_foreign` FOREIGN KEY (`contact_id`) REFERENCES `contacts` (`id`))

2/2 Connection.php第673行中的QueryException:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`myappdb`.`contact_addresses`, CONSTRAINT `contact_addresses_contact_id_foreign` FOREIGN KEY (`contact_id`) REFERENCES `contacts` (`id`)) (SQL: insert into `contact_address` (`phone_mobile`, `email`, `address_1`, `postcode`, `address_2`, `province`, `city`, `country`, `updated_at`, `created_at`) values (343434, , , , , , , , 2016-05-08 23:53:02, 2016-05-08 23:53:02))

我怀疑问题似乎是在为地址执行SQL插入时没有传递contact.id的外键,即使联系人本身已成功插入联系人表。

如何在两个表中创建新记录?

  • 我是否必须创建联系人,检索contact.id,然后再次使用它来保存地址?
  • 在我的db中删除sql外键约束是否更好?
  • 你会如何构建这个?

1 个答案:

答案 0 :(得分:1)

使用save方法。

public function store(Request  $request) { 
 $contact = Contact::create($request->except(["contact_address"]));
 $contact_address = new Contact_address($request->get('contact_address'));
 $contact->contact_address()->save($contact_address); 
 return back();
}